开发者

Can valueOf() return null according to Java conventions?

Is it acceptable to name a named constructor valueOf that may return null in some cases?

For example, bar() is a named const开发者_运维百科ructor that may return null if the argument is null.

class Foo {
    public static Foo bar(String value) {
        if (value == null)
            return null;
        else
            return new Foo();
    }
}

Would it be against the Java conventions to name it valueOf() instead? If not, I'm moving it to a helper.

EDIT: This method is a helper and must return null if the value is null for my needs.


Since that's not actually a constructor, you can do whatever you want with it. But you might want to think about throwing a NullPointerException instead of returning null if you are worried about your callers.


I see no problem with having a method like this return null, granted that you explicitly document the cases in which it will do so in the Javadoc summary so anyone who uses this method can understand when it will happen.

Also a slightly pedantic note: bar() is not a constructor.


In that case I would restrict the argument to be null. If it leads to null object to be returned, then it is wrong. So I would not bother my self with question can valueOf() return null. I would use IllegalArgumentException or NullPointerException in case of null argument.


Generally, I vote for no. In my experience, valueOf methods throw exceptions when they don't know how to convert the input. An argument can be made for returning null if the input was null, but that's the only case I can see.


As to me the best practice is to throw an NPE if the value is null and some other problem-oriented exception in case something else goes wrong. The main motivation behind that is that null is more for "unknown". I usually expect that instanceof test will return true when valueOf succeeded. This is not the case with null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜