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:
- Use the exact extraction for functions used internally, but the positive formulation for methods in interfaces; or
- 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.