Reputation: 1229
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
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
Reputation: 24801
Another simple method:
if ( Collections.emptyList().equals(data) ) { }
Upvotes: 1
Reputation: 849
I normally prefer && operators, for cases where the boolean algebra doesn't get too complex compared to a || expression.
Reason:
Upvotes: 1
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