Is there a more concise way to write this Java code?
This foo
that is returned by lookup
could be null
.
That's why I'm trying to avoid calling foo.getFooStr()
on a null
value by first retu开发者_运维问答rning null
if foo
is null
.
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. 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.
Why isn't there a lookup
that returns the appropriate foo string?
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. 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)!
Groovy does it nicer.
return lookup(input)?.fooStr
or even just:
lookup(input)?.fooStr
For Java 7, at some point it was planned that you could just write this:
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.
In Java8:
Optional.ofNullable(lookup(input)).map(f->f.getFooStr()).orElse(null);
精彩评论