Java clean code. 4 useful tips.

Dmitry Egorov
2 min readJun 30, 2018

--

Briefly:

  1. Use Optional for possible null objects.
  2. Use streams to iterate/filter/map/collect data
  3. Use functions/suppliers to reuse repeated code.
  4. Use generics

Avoid passing and comparing with null. Use optional instead.

Pass empty collections instead of null. (for them optional is extra). (like Collections.emptyList, Collections.EmptyMap,etc..)

Use java 8 stream to iterate/filter/map data.

In next example we convert string list to int list filtering negative values in old (for each) and new (stream) ways. Also we keep short way of list initialization Arrays.asList();

Use Functions/Suppliers to execute code as parameter. In next example we can see that code is almost the same. The only difference it’s function being executed:

So we can easily extract same part and pass only different part as supplier parameter:

But what if we need to return some value not just void instructions? Eg:

So in that case we can use old good generics!

Remember, elegant code is sign of senior skill.

--

--