Positive v. Exact Function Names

Robert C Martin recommends (in Clean Code) naming functions so that they fit in the exact use case. For example, assume you have an if-statement that accepts all values that do not contain $s:

if(input.indexOf("$") === -1)

Martin argues that the check should be extracted to exactly fit the case: [1]

function stringContainsNoDollarSigns(input) {
    return input.indexOf("$") === -1;
}

That makes the if-statement look like this:

if(stringContainsNoDollarSigns(input))

I would suggest an alternative: always implement for positive method names:

function stringContainsDollarSigns(input) {
    return input.indexOf("$") !== -1;
}

The resulting if-statement would now start with a programmatic “not” (!):

if(!stringContainsDollarSigns(input))

What are the pros and cons?

Implementing always the positive case means fewer functions when both the positive and negative can be expected. In this situation, implementing the exact case would (for consistency) mean implementing both stringContainsDollarSign and stringDoesNotContainDollarSign. That clearly results in some bad code duplication.

On the other hand, most functions in code are internal and only ever used once. In this case it does make sense to implement the exact case: there is no code duplication.

I would argue that programmers are so used to ! meaning “not” that always-positive implementations have a pretty much non-existent loss of comprehension.

In the end, I see two decent/acceptable code conventions:

  1. Use the exact extraction for functions used internally, but the positive formulation for methods in interfaces; or
  2. Always use the positive formulation of a boolean function.

Notes #

[1] Really, the more fitting way to do this would be to extend the string object, but that’s bad practice (cite) in Javascript. Ruby would allow (encourage, even) something like input.contains("$") or input.doesNotContain("$"). In fact, Ruby already has input.include? "$", but that’s not as readable.

 
3
Kudos
 
3
Kudos

Now read this

I wouldn’t recommend process

Back in February 2015 (a year ago!) I wrote that I wouldn’t recommend Scrum. Looking back I see that I was merely grasping at the end of a bigger concept. Here I will try to clarify and generalize from the original post. I would like to... Continue →