[英]Is there a more concise way to write this Java code?
This foo
that is returned by lookup
could be null
. lookup
返回的这个foo
可能是null
。
That's why I'm trying to avoid calling foo.getFooStr()
on a null
value by first returning null
if foo
is null
.这就是为什么我试图通过在
foo
为null
时首先返回null
来避免在null
值上调用foo.getFooStr()
。
But is there a better (more concise) way to write this?但是有没有更好(更简洁)的方式来写这个?
public static String getFooStr(String input)
{
Foo foo = lookup(input);
if(foo==null)
{
return null;
}
return foo.getFooStr();
}
You've two questions: is there a better way to write the code, and is there a more concise way to write the code.你有两个问题:有没有更好的方法来编写代码,有没有更简洁的方法来编写代码。
Regarding more concise , this could work:关于更简洁,这可以工作:
public static String getFooStr(String input) {
Foo foo = lookup(input);
return foo == null ? null : foo.getFooStr();
}
Regarding better : I value readability over conciseness any day, and by a wide margin.关于更好:我在任何时候都重视可读性而不是简洁性,而且差距很大。 Your original code looks fine to me.
您的原始代码对我来说看起来不错。 What matters is what looks good to you, and which is easier for you to understand and debug 3 months from now.
重要的是对您来说看起来不错,并且从现在起 3 个月后您更容易理解和调试。 I've heard someone say it best -- write your code so that is easily understandable by others, and even more importantly, by your future self.
我听说有人说得最好——编写你的代码,以便其他人容易理解,更重要的是,你未来的自己也能理解。
为什么没有返回适当的 foo 字符串的lookup
?
I'm not into java, but I do like clean code... Source code should be easy to read and understand for humans - the machine doesn't care how it looks but your colleagues do.我不喜欢java,但我喜欢干净的代码......源代码应该易于人类阅读和理解 - 机器不在乎它的外观,但你的同事会。 More concise code usually takes a moment or two longer to grasp (sometimes much longeer depending on the quantity and complexity).
更简洁的代码通常需要一两分钟的时间来掌握(有时会更长,具体取决于数量和复杂性)。 Keep code understandable and it will be maintainable (even if it is a bit more verbose)!
保持代码易于理解并且可以维护(即使它有点冗长)!
For Java 7, at some point it was planned that you could just write this:对于 Java 7,在某些时候计划你可以这样写:
public static String getFooStr(String input)
{
Foo foo = lookup(input);
return foo?.getFooStr();
}
But until this feature is widely known, you will have to stick to the ?:
operator.但在此功能广为人知之前,您将不得不坚持使用
?:
运算符。
I do not like multiple returns any where in any code.我不喜欢在任何代码中的任何位置多次返回。 I will just change it to
我将其更改为
public static String getFooStr(String input)
{
Foo foo = lookup(input);
String fooString;
if(foo!=null)
{
fooString = foo.getFooStr();
}
return fooString;
}
Also the version from @Hovercraft Full Of Eels is good in my opinion but less readable but still a common way of doing.在我看来,来自@Hovercraft Full Of Eels 的版本也不错,但可读性较差,但仍然是一种常见的做法。
在 Java8 中:
Optional.ofNullable(lookup(input)).map(f->f.getFooStr()).orElse(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.