[Logo]
Forums Register Login
Java Best practices - Clean Code
clean code book contains a statement :

The method should not invoke the methods on objects that are returned by any of allowed functions
e.g
because it calls getScratchDir() on return value of getOptions() and then getAbsolutePath() on return value of getScratchDir();



But modifying above as :
doesn't it make the code more complex. A single line code converted to multiple line.
Also, are not the JDK functions meant to be use anywhere as they are(such as getAbsolutePath), without calling them in separate functions.

Please clarify me if I misunderstood something.
ok I understood it. The code should be like:

it is written and explained further in book. Doubts cleared
Don't know what that book focus on, but functional programming states the opposite. In particular, afaik, with the introduction of the stream (in Java >= 8), it is common practice to call method in "cascade" style.
 

Stefano Carniel wrote:Don't know what that book focus on, but functional programming states the opposite. In particular, afaik, with the introduction of the stream (in Java >= 8), it is common practice to call method in "cascade" style.


your statement is making me confused
The book is about writing clean quality codes.
If you can, take a look at this book. It explains very well these concepts, not only, it teaches how to implement classes that support this programming style (methods cascade).
Honestly, what your book states is not in contrast whith what mine states. Functional programming can help to essentially produce safer and more concise code, but for sure this code is less readable (but not necessarily less clean).
Although I'm a huge fan of chained method calls, it makes your code less readable - unless you use some tricks that is. For instance, I always put each filter and map call on its own line. The above example would be just as readable if you just add some line breaks:

This has two advantages:
1) It's more readable.
2) NullPointerExceptions are reported on the line they are caused by. With a one-liner, you couldn't tell the difference if ctxt was null, or if ctxt.getOptions() returned null, or if ctxt.getOptions.getScratchDir() returned null - they would all originate from the same line. With my example there would be three different lines for the three different causes.


Note that I almost never put the first call on a separate line, unless if all calls are similar, like StringBuilder.append or the String.replace example from https://coderanch.com/t/685210/java/String-replace-working#3216365.

This thread has been viewed 305 times.

All times above are in ranch (not your local) time.
The current ranch time is
Sep 22, 2018 20:09:55.