1

Replace Nested Conditions with Guard Clauses

by volkanuzun 14. April 2009 08:22

   I am reading “Applying Domain-Driven Design and Patterns with Examples in C# and .NET” by Jimmy Nilsson. I am at the very beginning of the book, and the book already is proved to be very useful for me. I put a post-it page with a small note on it, reminding myself what i should be checking out after I am done with the book. This book has already gotten a lot of post-its :)

One of my notes has this on it: “Replace Nested Conditions with Guard Clauses” (Martin Fowler Refactoring). I search on this phrase, and basically this is what it means I guess:
Let’s say in your code you have some if-else clauses, usually what if-else clause says, each possibility (if being true, or if being false) has almost the same weight, even whatever you are testing in one branch  is a rare condition.

Below is a calculator class, that can  divide numbers:

public class Calculator
{
    public int Number1;
    public int Number2;
    
    public Calculator(int Number1, int Number2)
    {
        this.Number1 = Number1;
        this.Number2 = Number2;
    }
    public Calculator():this(0,0){}
    
    public double Divide()
    {
         if(Number2==0) 
             throw ArgumentException();
         else if(Number1==0)
              return 0;
        else
            return (double)Number1/Number2*1.0;
     }
}

This is a simple class, and divide function, first checks the numbers, and throws exception or returns 0 or returns division. There is 1 if clauses with 2 else clauses. We first check if Number2 is zero or not, as any number divided by zero will throw runtime error, this  check is an unusual condition check, as the application is not expecting a zero, and shouldn't get one. This unusual conditional  should be not followed with an else clause, but return back the caller. This is called a guard clause, so if we refactor the divide function we will get this:

if (Number2==0)
    throw new ArgumentException();
if(Number1==0)
    return 0;
return (double)Number1/Number2*1.0;
This new code is clearer, easier to understand and maintain :)
 

Tags:

Comments

pingback
netdeluxo.com
4/14/2009 2:54:37 PM #

Pingback from netdeluxo.com

Replace Nested Conditions with Guard Clauses | Webmaster Tools

Comments are closed

Powered by BlogEngine.NET 1.6.0.0
Original Design by Laptop Geek, Adapted by onesoft