Over a million developers have joined DZone.
Platinum Partner

Clean Code: Conditionals

· DevOps Zone

The DevOps Zone is brought to you in partnership with New Relic.  Learn more about the common barriers to DevOps adoption so that you can come up with ways to win over the skeptics and kickstart DevOps.

This is part of a series of micro-blogs (somewhere between a tweet and a full on blog) on Clean Code. In this post, I’m going to focus on one big culprit in obfuscated, not clear clean code — Conditionals (i.e. if statements). Let’s look at an example:

function handleSearchRequests(req, res) {
    if (req.params['toggle'] === 'A') {
        doToggleSearch(req.params, res);
    } else {
        doRegularSearch(req.params, res);
    }
}

While this looks pretty straightforward, this is a code smell and is a broken pane waiting for the crack to grow bigger. What does this code actually convey? This is not entirely clear to anyone else, except probably the person who wrote it.

Quick Fix

Make all conditionals only use local variables that identify the role they are playing. So, in this case the code becomes:

function handleSearchRequests(req, res) {
    var isAToggleSearch = (req.params['toggle'] === 'A');
    if (isAToggleSearch) {
        doToggleSearch(req.params, res);
    } else {
        doRegularSearch(req.params, res);
    }
}

Here we are doing two things:

1. We are clearly identifying this concept of a toggleSearch and being very explicit about what is and is not a toggleSearch.
2. In our conditional we are making the branching more obvious and explicit.

TL; DR

By just going through this exercise of using local role playing variables in conditionals you’ll be surprised on just how much clearer your code becomes.



The DevOps Zone is brought to you in partnership with New Relic. Quickly learn how to use Docker and containers in general to create packaged images for easy management, testing, and deployment of software.

Topics:

Published at DZone with permission of Santosh Kumar , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}