Some tips to make your coding life easier

Photo by Markus Spiske on Unsplash

It does not matter whether you’re hunting a bug in legacy code or reviewing the code you wrote last year, there are moments that you struggle and waste all of your mental energy on that single hard-to-grasp logical condition 😐.

I’m going to show you some simple techniques that will help you to make the conditions easier to understand and analyze so you won’t have to spend so much time on it anymore 😇.

De Morgan’s Laws

First of all, I would like to mention (or remind) you of De Morgan’s laws:

the negation of a disjunction is the conjunction of the negations; and

the negation of a conjunction is the disjunction of the negations;

(…)

or

not (A or B) = not A and not B; and not (A and B) = not A or not B

In a programming world it would be expressed as:

!(a || b) == !a && !b ; and

; and !(a && b) == !a || !b

De Morgan’s laws are worth applying for example if a negated condition consists of multiple negated variables. Just look at what happens when you negate the variables:

The laws apply also for the comparison operators:

You might apply the rules to the condition itself and/or sub-conditions as well.

The Truth Table

The Truth Table can help you find correlations between the variables. The table describes all possible states of a given condition. It consists of columns for every variable in the shape and additional column for the result.

For example the table for (!a && b) || (a && !b) looks like:

Truth table of (!a && b) || (a && !b)

Please note — I’m using 0 for false and 1 for true , so the tables are compact and easy to read.

Looking at the table you can see the condition gives true only when both variables differ from each other so it can be simply described as a != b .

The condition can be expressed as

sum (disjunction) of the “true” combinations

negation of sums of the “false” combinations:

For our example of (!a && b) || (a && !b) :

sum of the “true” combinations, so the condition itself: (!a && b) || (a && !b)

negation of sums of the “false” combinations: !((!a && !b) || (a && b)) which can be simplified to (a || b) && (!a || !b) (De Morgan Law )

Okay, let’s dive into some examples!