转移所有权的方法的命名约定
考虑以下示例:
class Foo
{
private Bar x;
// ...
public Bar getAndResetX()
{
Bar result = x;
x = new Bar();
return result;
}
}
此类方法是否有既定的命名约定?比如yieldX
、transferX
之类的?
Consider the following example:
class Foo
{
private Bar x;
// ...
public Bar getAndResetX()
{
Bar result = x;
x = new Bar();
return result;
}
}
Is there an established naming conventions for such methods? Like yieldX
, transferX
or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我们过去使用约定 Adopt 和 Orphan 作为前缀,以在方法名称中提供意图(摘自 Taligent 关于 C++ 的书籍)。
您可以使用类似的方法来提供对象的所有权线索。坦率地说,尽管我会坚持使用添加和删除的Java约定。它们提供了足够的意图,其他程序员将不需要阅读解释新约定的注释。
We used to have the convention Adopt and Orphan as a prefix to provide intention in the method name (taken from Taligent book on C++).
You could use something similar to provide ownership clues to the objects. Quite frankly though I would stick with the Java convention of using add and remove. They provide enough intention and other programmers will not need to read a comment explaining the new convention.
我不确定此类方法是否有命名约定。恕我直言,我会使用动词take(例如
takeX()
)。有关方法命名约定的详细信息,请参阅 JLS § 6.8.3 方法名称。但老实说,这实际上只是一个意见问题。如果您真的很担心,我建议您浏览 Java API 用于功能等效的方法,然后根据这些方法命名您的方法。
I'm not sure that there is a naming convention for such methods. IMHO, I would use the verb take (e.g.
takeX()
). For more information regarding method naming conventions, see JLS §6.8.3 Method Names.But in all honesty, it's really just a matter of opinion. If you're really that concerned, I'd recommend you browse the Java API for methods that are functionally equivalent, and then model your method name after those.
Mozilla 的本机智能指针类使用
forget()
方法来指示所有权转移:Mozilla's native smart-pointer classes use the method
forget()
to indicate a transfer of ownership: