Over a million developers have joined DZone.

Clean Code: Conditionals

· DevOps Zone

Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

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.



Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.

Topics:

Published at DZone with permission of Santosh Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}