Click here to Skip to main content
15,900,378 members
Articles / All Topics

Robert’s Rules of Coders: #8 Avoid Negative Conditionals And Method Names

Rate me:
Please Sign up or sign in to vote.
4.55/5 (10 votes)
14 Feb 2016CPOL4 min read 19.4K   4   5
Robert’s Rules of Coders: #8 Avoid Negative Conditionals And Method Names

When you write code, you should almost always assume that another person will attempt to read and understand that code some day in the future. That person could be your future self. Therefore, it is in your best interest to write code that can be quickly and easily understood by people, in addition to providing the correct instructions to the computer. Two ways to do this are to avoid negative conditions and negative words in method and variable names.

Avoid Negative Conditions

Let’s consider the following two ways you could write a bit of logic:

You could write:

If a > b then ... //If a is greater than b

Or you could write:

If a !<= b then ... //If a is not less than or equal to b

A computer will understand both ways equally well, but it usually takes humans a little longer to understand the second way than the first. And when another developer adds a little more logic to the statement, it takes humans even longer to figure out as shown in the next two statements:

You could write:

If a > b and c > a then ... //If a is greater than b and c is greater than a

Or you could write:

If a !<= b and c !<= a then ... //If a is not less than or equal to b and c is not less than or equal to a

When developers see the second way above, they will probably write down numbers on a piece of paper to help them deduce the logic, even though ultimately it is the same as the first way. Of course, changing the sequence of the conditions can also make the logic more readable, but in some languages, that may come with a performance impact.

Consider Performance Impact of Condition Sequence

You could write:

If a > b and c > a then ...

as:

If c > a and a > b then ...

Both ways provide the same output, but many languages will only evaluate the second condition if the first condition is true. This happens because the language is smart enough to realize that if the first half of the statement is false, then the entire statement will be false. So in some cases, like in the methods below, it is probably more efficient to write the code the first way than the second way even though the results are the same:

The first, more efficient way to write the code:

If FastMethodThatReturnsTrueHalfTheTime() == true and SlowMethodThatUsuallyReturnsFalse() == true then...

The second, less efficient way to write the code:

If SlowMethodThatUsuallyReturnsFalse() == true and FastMethodThatReturnsTrueHalfTheTime() == true then...

Avoid Negative Words in Method Names

We often include method names in our ‘if’ statements and therefore we should probably avoid negative terms in the names of our methods. Consider the following examples of a method that checks for hyphens in a string:

String streetName = "Happy-Road"
If StringContainsHyphen(streetName) Then ...
If StringDoesNotContainHyphen(streetName) Then ...

The two statements above both seem easy to understand, but what happens if a coder checks if the results are false? Notice that it gets more difficult to interpret the second statement that contains the negative word “Not” in the name.

If StringContainsHypen(streetName) == false Then ...
If StringDoesNotContainHypen(streetName) == false Then ...

Avoid Negative Words in Variable Names

The guidance to avoid negative words in method names holds similar value for variable names, particularly the names of boolean variables.

We could name a boolean blnCountExceedsMaximum, or blnCountDoesNotExceedMaximum. We could also name it blnCountIsBelowMaximum or blnCountIsNotBelowMaximum. Now look at the following four statements and decide for yourself which is easiest to understand.

If blnCountExceedsMaximum == false then ...
If blnCountDoesNotExceedMaximum== false then ...
If blnCountIsBelowMaximum == false then ...
If blnCountIsNotBelowMaximum== false then ...

If you are like me, the second and fourth statements take a little longer to understand than the first and third.

Should You Include “Is True” and “Is False”?

I have one last topic I think you should consider when writing ‘if’ statements. Should you include the “== true” and “==false”, or just leave the variable without that? A lot of languages do not require those values. The computer handles the following two statements equally well.

If blnSuccess == true
If blnSuccess

Personally, I don’t think it usually matters too much and I tend to code both ways. Sometimes, usually when my if statement has a method call in it or multiple conditions in it, I will include the “== true” or “== false” because I believe it adds clarity:

If (ExportDataToFile() == true and LastExportSucceeded == false) then

If you are going to test if a non-boolean variable is true or false, then I recommend including the “== true” or “== false” to let the next programmer know that this is what you intended.

//You could test if "number of failures" is not equal zero this way
If NumberOfFailures == true

//Or you could test if "number of failures" is not equal zero this way
If NumberOfFailures

In the second statement, it is not obvious that you intended to test the number as a boolean. Another programmer looking at the code might think you accidentally left part of the code out of the program. Rather than use either of those statements, it would probably be best to write:

If NumberOfFailures != 0

As with any of Robert’s Rules of Coding, you don’t need to adhere to them all of the time and there are cases where it is better not to. But most programmers should follow the rules most of the time. I hope you agree.

Go to Robert’s Rules of Coders for more.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Kraft Software LLC
United States United States
Rob Kraft is an independent software developer for Kraft Software LLC. He has been a software developer since the mid 80s and has a Master's Degree in Project Management. Rob lives near Kansas City, Missouri.

Comments and Discussions

 
SuggestionDe Morgan's laws Pin
sx200815-Feb-16 8:00
sx200815-Feb-16 8:00 
I think you should mention the De Morgan's laws[^].
Let's make up a fictive example:

C#
if(!taxRulesLoaded || (taxrate <= 0.0) || (bruttoincome <= 0.0))
   throw new Exception("can't calculate income");
Using de Morgan's law we can refactor it to this:
C#
bool success = taxRulesLoaded && (taxrate > 0.0) && bruttoincome > 0.0;
if(!success)
  throw new Exception("can't calculate income");
Both snippets are equivalent - it depends on the circumstances; sometimes it looks better after applying de Morgan's law.
GeneralOne nit-pick and one comment Pin
AlGonzalez26-Jan-16 10:18
AlGonzalez26-Jan-16 10:18 
GeneralRe: One nit-pick and one comment Pin
Rob Kraft14-Feb-16 12:35
professionalRob Kraft14-Feb-16 12:35 
QuestionAvoid negative conditions? Pin
PeejayAdams22-Jan-16 3:27
PeejayAdams22-Jan-16 3:27 
AnswerRe: Avoid negative conditions? Pin
Rob Kraft22-Jan-16 4:45
professionalRob Kraft22-Jan-16 4:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.