Recently I was making changes to some code that was at least 10 years old. Being so old, the identity of the “guilty” party (or parties) has long since been lost to the sands of time. I cannot even say that I am not said party. 😁 The code in question looked similar to the following block of code.
if (inventTable.FlagField && custTable.FlagField)
{
this.doSomeProcess();
}
if (!inventTable.FlagField || !custTable.FlagField)
{
this.doSomeOtherProcess();
}
Think about this code for a moment. I will wait.
What is wrong with the code is that the conditions of the two if statements are logically opposite (see De Morgan’s law). Actually, “wrong” might not be the correct word but it is unnecessarily complex. The block of code can be written as the following.
if (inventTable.FlagField && custTable.FlagField)
{
this.doSomeProcess();
}
else
{
this.doSomeOtherProcess();
}
In the field of electronics, people use Boolean algebra to design and to simplify electronic circuits. Despite the subject’s usefulness to coding, not all developers get exposure to this branch of mathematics. This is unfortunate because knowing it gives developers a tool to simplify complicated logical expressions and to improve the readability of code.
If you are interested in learning more, here are some links to help you get started.