开发者

naming convention for methods that transfer ownership

Consider the following example:

class Foo
{
    private Bar x;

    // ...

    public Bar getAndResetX()
    {
        Bar result = x;
        x = new Bar();
        ret开发者_运维技巧urn result;
    }
}

Is there an established naming conventions for such methods? Like yieldX, transferX or something?


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


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'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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜