Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning early from a function more elegant than an if statement?

Tags:

Myself and a colleague have a dispute about which of the following is more elegant. I won't say who's who, so it is impartial. Which is more elegant?

public function set hitZone(target:DisplayObject):void
        {
            if(_hitZone != target)
            {
                _hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
                _hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
                _hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);

                _hitZone = target;

                _hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
                _hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
                _hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);
            }
        }

...or...

public function set hitZone(target:DisplayObject):void
        {
            if(_hitZone == target)return;

            _hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
            _hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
            _hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);

            _hitZone = target;

            _hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
            _hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
            _hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);

        }
like image 336
Iain Avatar asked Dec 10 '08 10:12

Iain


People also ask

Should I return from a function early or use an IF statement?

One of the reasons that you could consider using early returns is that it keeps your code visually flatter. There is no need for extra indentation that you would have had if you went for the alternative route that uses a wrapping if-statement. This makes code more readable.

What does return do if statement?

The return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was called.

What is early return in programming?

R eturn early is the way of writing functions or methods so that the expected positive result is returned at the end of the function and the rest of the code terminates the execution (by returning or throwing an exception) when conditions are not met.

What function will return if the return statement does not exist a 0 B 1 C 1 D None?

Hence the data type is tuple. 8. If a function doesn't have a return statement, which of the following does the function return? Explanation: A function can exist without a return statement and returns None if the function doesn't have a return statement.


2 Answers

In most cases, returning early reduces the complexity and makes the code more readable.

It's also one of the techniques applied in Spartan programming:

Minimal use of Control

  1. Minimizing the use of conditionals by using specialized constructs such ternarization, inheritance, and classes such as Class Defaults, Class Once and Class Separator
  2. Simplifying conditionals with early return.
  3. Minimizing the use of looping constructs, by using action applicator classes such as Class Separate and Class FileSystemVisitor.
  4. Simplifying logic of iteration with early exits (via return, continue and break statements).

In your example, I would choose option 2, as it makes the code more readable. I use the same technique when checking function parameters.

like image 182
xsl Avatar answered Sep 20 '22 15:09

xsl


This is one of those cases where it's ok to break the rules (i.e. best practices). In general you want to have as few return points in a function as possible. The practical reason for this is that it simplifies your reading of the code, since you can just always assume that each and every function will take its arguments, do its logic, and return its result. Putting in extra returns for various cases tends to complicate the logic and increase the amount of time necessary to read and fully grok the code. Once your code reaches the maintenance stage then multiple returns can have a huge impact on the productivity of new programmers as they try to decipher the logic (its especially bad when comments are sparse and the code unclear). The problem grows exponentially with respect to the length of the function.

So then why in this case does everyone prefer option 2? It's because you're are setting up a contract that the function enforces through validating incoming data, or other invariants that might need to be checked. The prettiest syntax for constructing the validation is the check each condition, returning immediately if the condition fails validity. That way you don't have to maintain some kind of isValid boolean through all of your checks.

To sum things up: we're really looking at how to write validation code and not general logic; option 2 is better for validation code.

like image 33
Mark Kegel Avatar answered Sep 20 '22 15:09

Mark Kegel