In If else branches, what is the preferred approach?

cyphx :

I am writing a validation function, which checks a multitude of conditions and returns Success if none of the checks fail. I want to know, what would be the preferred way among two choices and why ?

private ResponseObj validationFunc1(ObjA objA, ObjB objB, ObjC objC){
ResponseObj responseObj = new ResponseObj();
if(condA){
   responseObj.setStatus("FAILURE");
   responseObj.setMessage("condA message");
   return responseObj;
} else if(condB){
   responseObj.setStatus("FAILURE");
   responseObj.setMessage("condB message");
   return responseObj;
} ....
...
}else if(condZ){
   responseObj.setStatus("FAILURE");
   responseObj.setMessage("condZ message");
   return responseObj;
}
responseObj.setStatus("SUCCESS");
responseObj.setMessage("Valid");
return responseObj;
}


private ResponseObj validationFunc2(ObjA objA, ObjB objB, ObjC objC){
if(condA){
   return new ResponseObj("FAILURE","condA message");
} else if(condB){
   return new ResponseObj("FAILURE","condB message");
} ....
...
}else if(condZ){
   return new ResponseObj("FAILURE","condZ message");
}
return new ResponseObj("SUCCESS","Valid");
}

Which of the above 2 functions would be preferred in production code ? If so, does one method has a performance gain over another ? Or, Am I just mistaken and the compiled code for both the functions will be same ?

Thanks in advance for your answers. If I have asked the same question again, I am very sorry. I did try my best to search for this.

GhostCat salutes Monica C. :

Which of the above 2 functions would be preferred in production code

Neither one.

Good code follows certain rules, especially for Java, nicely formulated in the "Clean Code" book by Robert Martin. Things that clean code strongly advocates against:

  • high number of parameters (and 2 is consider high already ;-)
  • doing multiple "things" within one method/class

So, at least for some people, (well written) production code would look much different.

What you could do for example: define an interface Validator, and then put each different validation into its own class implementing that interface. And then "multiple" checks turns into instantiating each of those classes, and putting the objects in some List<Validator> ... when you then iterate, and apply one after the other.

And note: performance doesn't matter here, too. The only thing that matters is how easy to read, understand, and maintain your code is. At least for me, the above ... isn't very good at that, for the reasons stated above.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142175&siteId=1