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

This foo returned by lookup may be null .

This is why I am trying to avoid calling foo.getFooStr() by null by first returning null if foo is null .

But is there a better (shorter) way to write this?

 public static String getFooStr(String input) { Foo foo = lookup(input); if(foo==null) { return null; } return foo.getFooStr(); } 
+6
source share
6 answers

You have two questions: is there a better way to write code, and is there a more concise way to write code.

As for the more concise , this might work:

 public static String getFooStr(String input) { Foo foo = lookup(input); return foo == null ? null : foo.getFooStr(); } 

Relatively better . I appreciate readability for brevity any day and by a wide margin. Your original code looks good to me. What matters is what is good for you and what is easier for you to understand and debug after 3 months. I heard someone say it best - write your code so that it is easy for others to understand, and more importantly, your future self.

+34
source

Why is there no lookup that returns the corresponding string foo?

+6
source

I'm not in java, but I like clean code ... The source code should be easy to read and understand for people - the machine does not care what it looks like, but your colleagues. More concise code usually takes one to two hours to grab (sometimes many long-livers, depending on quantity and complexity). Keep the code clear and it will be supported (even if it is a little more verbose)!

+3
source

Groovy does it better .

return lookup(input)?.fooStr

or even just :

lookup(input)?.fooStr

+3
source

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 function is widely known, you have to stick with the ?: Operator.

+2
source

I don't like multiple returns wherever they are in any code. I 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 common.

+1
source

Source: https://habr.com/ru/post/897118/


All Articles