Refactoring: Usage of Guard Clauses

Standard

During initial days of development, I inclined towards using nested if statements, but with passage of time when code requirements started to be more complex and involve lot of if statements, this result in nightmare in terms of maintenance and readability of code. So I started using Guard clauses to improvise readability and duplication of code.

Before Guard Clause code::

[HttpPost]
public Candidate AddUpdateCandidateDependents(Candidate newObject)
{
    if (newObject == null)
    {
        if (newObject.ID == 0)
        {
            Candidate obj = newtObject;
            obj.ID = GetCandidateDetailId();
            obj.Active_f = true;
            _context.CandidateDependents.Add(obj);
            _context.SaveChanges();
            return obj;
        }
        else
            return null;
    }
    else
        return null;
}

After Guard Clause code:

[HttpPost]
public Candidate AddUpdateCandidateDependents(Candidate newObject)
{
    if (newObject == null || newObject.ID == 0) return null;
    Candidate obj = newObject;
    obj.ID = GetCandidateDetailId();
    obj.Active_f = true;
    _context.CandidateDependents.Add(obj);
    _context.SaveChanges();
    return obj;
}

Please note we can however combine above two if statements, When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for !=

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s