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 returning 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)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With