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

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.

Leave a Comment