Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there benefits to quick-exiting a method or constructor?

I believe this to be related partially to short-circuiting logic, but I couldn't find any questions that directly answered my question. Possible related questions: Benefits of using short-circuit evaluation, Why use short-circuit code?

Consider the following two code blocks, both of which are possible constructors for a class

public MyClass(OtherClass other){
    if (other != null) {
       //do something with other, possibly default values in this object
    }
}

and this

public MyClass(OtherClass other){
    if (other == null)  return;

    //do something with other, possibly default values in this object
}

Is there any benefit to doing the latter over the former? There is no other code that follows in the constructor, just code that uses the other object to construct this one.

like image 929
Thomas Jones Avatar asked Dec 06 '22 15:12

Thomas Jones


2 Answers

This a case where you should do what is the most readable to you and your coworkers. There is unlikely any perceivable speed difference between the two approaches.

like image 77
JaredPar Avatar answered Dec 09 '22 03:12

JaredPar


The only difference is readability. With what you call "quick exit", you can stop thinking about what conditional you're inside of, because you're not inside of one anymore.

like image 27
John Saunders Avatar answered Dec 09 '22 03:12

John Saunders