Friday, December 21, 2012

Coding tip: early exit

In this series of 'coding tips' articles I will show you some of the lesson learned tips I am using on a daily basis during development. They are general purpose tips which can easily be adapted to most development languages.

The first one is what I call Early exit

Early exit:

Put the exit (or return) conditions on the top of a code block.

Example in C:


   if (error) { // Early exit when 'error'
      fprintf(stderr, "Error: %s", error.message);


      Other statements



It is really straightforward and helps you identify shortest execution paths. Plus it helps getting rid of if/then/else blocks and improves readability.

So my personal rating for this coding tip is:

Performance 2/5
Readability 4/5
Sustainability 3/5

No comments:

Post a Comment