Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more concise way to write this Java code?

Tags:

java

null

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();
}
like image 954
Brandon Pike Avatar asked Sep 11 '11 22:09

Brandon Pike


3 Answers

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.

like image 182
Hovercraft Full Of Eels Avatar answered Nov 11 '22 03:11

Hovercraft Full Of Eels


Why isn't there a lookup that returns the appropriate foo string?

like image 28
Daniel A. White Avatar answered Nov 11 '22 03:11

Daniel A. White


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)!

like image 3
Jon Gilbert Avatar answered Nov 11 '22 03:11

Jon Gilbert