转移所有权的方法的命名约定

发布于 2024-12-04 03:05:30 字数 270 浏览 2 评论 0原文

考虑以下示例:

class Foo
{
    private Bar x;

    // ...

    public Bar getAndResetX()
    {
        Bar result = x;
        x = new Bar();
        return result;
    }
}

此类方法是否有既定的命名约定?比如yieldXtransferX之类的?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

天邊彩虹 2024-12-11 03:05:30

我们过去使用约定 AdoptOrphan 作为前缀,以在方法名称中提供意图(摘自 Taligent 关于 C++ 的书籍)。

Bar b = foo.orphanBar(); // take Bar out of Foo
foo.adoptBar(b); // put it right back in

您可以使用类似的方法来提供对象的所有权线索。坦率地说,尽管我会坚持使用添加删除的Java约定。它们提供了足够的意图,其他程序员将不需要阅读解释新约定的注释。

Bar b = foo.removeBar(); // take Bar out of Foo
foo.addBar(b); // put it right back in

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++).

Bar b = foo.orphanBar(); // take Bar out of Foo
foo.adoptBar(b); // put it right back in

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.

Bar b = foo.removeBar(); // take Bar out of Foo
foo.addBar(b); // put it right back in
醉城メ夜风 2024-12-11 03:05:30

我不确定此类方法是否有命名约定。恕我直言,我会使用动词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.

木緿 2024-12-11 03:05:30

Mozilla 的本机智能指针类使用 forget() 方法来指示所有权转移:

already_AddRefed<nsIFoo> GetFoo() {
    nsCOMPtr<nsIFoo> foo = ...
    ...
    return foo.forget();
}

Mozilla's native smart-pointer classes use the method forget() to indicate a transfer of ownership:

already_AddRefed<nsIFoo> GetFoo() {
    nsCOMPtr<nsIFoo> foo = ...
    ...
    return foo.forget();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文