Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Clean Code: Conditionals

DZone's Guide to

Clean Code: Conditionals

· DevOps Zone
Free Resource

“Automated Testing: The Glue That Holds DevOps Together” to learn about the key role automated testing plays in a DevOps workflow, 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.



Learn about the importance of automated testing as part of a healthy DevOps practice, 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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}