Refactoring For Prose

Written by Eric L. Barnes - - Aggregated on Tuesday December 11, 2018
Tags: writing

I’ve worked with a lot of legacy applications and one thing that I have seen many times is small things that are confusing. For example, I recently came across some code that looked like this:

if ($foo) {


    $noAction = true;


} else {


    $noAction = false;


}

That is pretty straightforward and easy to grasp. But what comes next is where the problem lies:

if (! $noAction) {


    //...


}

If we read this as a sentence it says, “if not no action” and most of us struggle figuring out what the double negative translates too. It’s not something that we encounter very often in English so when we see it our brains turn to mush.

From my experience things like this are common in older procedural code because you are defining the variable so far away from the use that it either morphed into the current style over time, or the variable is used in several different contexts and this was the path of least resistance when it was originally coded.

While you are coding try to think through things like you are writing prose. In this example, maybe something as simple as renaming the variable to $doAction would be sufficient.

if ($foo) {


    $doAction = false;


} else {


    $doAction = true;


}




if($doAction) {


    //... 


}

In my opinion reading “if do action” is much clearer and easy to grasp.


« Open Source and Squeegee Men - Paul M. Jones

Yegor Bugayenko - Unit Testing Anti-Patterns, Full List »