Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 856
artjomka Avatar asked Dec 22 '22 17:12

artjomka


2 Answers

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

like image 44
CloudyMarble Avatar answered Dec 28 '22 23:12

CloudyMarble


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.

like image 106
AlexR Avatar answered Dec 29 '22 01:12

AlexR