artjomka
artjomka

Reputation: 1229

Returning from method with return command

There is a method in some class

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

Information from data list is essential for this method - that means if data is empty or null no logic in this method is executed. I have two options how to do that

First

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

Second

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

Which option would you prefer and why ? Thanks !

Upvotes: 4

Views: 131

Answers (4)

CloudyMarble
CloudyMarble

Reputation: 37576

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 separated section of code.

And this will enable you in the future to centraly separate and extend if necessary all conditions which will cause you to leave the routine instead of having lots of nested if's. Consider that the rate code is writen:read about 1:10

Upvotes: 3

Suraj Chandran
Suraj Chandran

Reputation: 24801

Another simple method:

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

Upvotes: 1

Patrick
Patrick

Reputation: 849

I normally prefer && operators, for cases where the boolean algebra doesn't get too complex compared to a || expression.
Reason:

  1. there is only one case (out of four) to check mentally to enter the if statement.
  2. I try to avoid return/break expressions in methods to make the code flow clearer.

Upvotes: 1

AlexR
AlexR

Reputation: 115418

The second option is definitely better because it does not increase the code nesting, easier for reading and understanding. You can also add more rules when not to do the operation and this does not affect the important part of the implementation.

Upvotes: 6

Related Questions