Returning from a method using the return command

In some class

there is a method

public void addAdditionalData(List<PairOfKeyString> data, List<Text> comments)

Information from the data list is important for this method - this means that if the data is empty or empty, the logic in this method is not executed. I have two options for how to do this.

First

if (data != null && !data.isEmpty()) { do somelogic here }

Second

 if(data == null || data.isEmpty()) { return; } 

Which option would you prefer and why? Thanks!

+4
source share
4 answers

The second option is definitely better, because it does not increase the nesting of the code, it is easier to read and understand. You can also add additional rules if you do not perform the operation, and this does not affect an important part of the implementation.

+6
source

I prefer the second option:

 if(data == null || data.isEmpty()) { return; } 

As you can add your logic after that without having to encapsulate all the code in the if statement, which makes your code less readable, the reader will see it as a separate section of the code.

And this will allow you in the future to centrally split and, if necessary, expand all the conditions that will force you to leave this routine instead of having a lot of nested if. Consider speed code written: read about 1:10

+3
source

I usually prefer && operators, for cases where Boolean algebra does not get too complicated compared to || expression.
Cause:

  • there is only one case (out of four) to check mentally in order to introduce an if statement.
  • I am trying to avoid return / break expression in methods to make the code stream more understandable.
+1
source

Another easy way:

if (Collections.emptyList (). Equals (data)) {}

+1
source

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


All Articles