根据 Java 约定,valueOf() 可以返回 null 吗?
命名一个在某些情况下可能返回 null
的命名构造函数 valueOf
是否可以接受?
例如,bar()
是一个命名构造函数,如果参数为 null
,则可能返回 null
。
class Foo {
public static Foo bar(String value) {
if (value == null)
return null;
else
return new Foo();
}
}
将其命名为 valueOf()
会违反 Java 约定吗?如果没有,我就把它交给帮手。
编辑:此方法是一个帮助器,如果该值为 null 以满足我的需要,则必须返回 null。
Is it acceptable to name a named constructor valueOf
that may return null
in some cases?
For example, bar()
is a named constructor 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于它实际上不是一个构造函数,因此您可以用它做任何您想做的事情。但如果您担心调用者,您可能需要考虑抛出
NullPointerException
而不是返回null
。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 returningnull
if you are worried about your callers.我认为使用这样的方法返回
null
没有问题,假设您明确在 Javadoc 摘要中记录了它将执行此操作的情况,以便任何使用此方法的人可以理解它什么时候会发生。还有一个稍微迂腐的注释:
bar()
不是构造函数。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.在这种情况下,我会将参数限制为
null
。如果它导致返回null
对象,那么它是错误的。所以我不会用valueOf()
是否可以返回null
的问题来打扰自己。如果参数为空,我会使用 IllegalArgumentException 或 NullPointerException 。In that case I would restrict the argument to be
null
. If it leads tonull
object to be returned, then it is wrong. So I would not bother my self with question canvalueOf()
returnnull
. I would useIllegalArgumentException
orNullPointerException
in case of null argument.一般来说,我投反对票。根据我的经验,
valueOf
方法在不知道如何转换输入时会引发异常。如果输入为 null,则可以提出返回 null 的参数,但这是我能看到的唯一情况。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.对我来说,最佳实践是如果值为 null 则抛出一个 NPE,并在出现其他问题时抛出一些其他面向问题的异常。其背后的主要动机是
null
更多地表示“未知”。我通常期望当valueOf
成功时,instanceof
测试将返回 true。null
的情况并非如此。As to me the best practice is to throw an
NPE
if the value isnull
and some other problem-oriented exception in case something else goes wrong. The main motivation behind that is thatnull
is more for "unknown". I usually expect thatinstanceof
test will return true whenvalueOf
succeeded. This is not the case withnull
.