Platinum Partner
java,devops,tips and tricks

Clean Code: Conditionals

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.



Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}