Why is it important to express the code in disjunctive normal form?

The company I work for recently had a mandate that all “very visible” logical logic should be expressed in a disjunctive normal form.

So, for example (although the concept is an agnostic of the language),

#if (defined(A) || defined( B )) || (defined(C) && defined(D)) 

had to be replaced by:

 #if defined(A) || (defined(C) && defined(D)) || defined(B) 

What is the motivation for indicating that code should be expressed this way? What are the benefits?

+4
source share
3 answers

The advantage is that expressing such logic in canonical / normalized form everywhere inside the code base (theoretically) will make it easier for programmers to understand and support.

Without such a rule, some programmers tend to “optimize” the expression in such a way that it becomes difficult for the developer to unravel it. In addition, the regular form makes it easier to create new expressions if necessary.

(These advantages are controversial. As with any stylistic guide, adhering to a consistent rule is more important than choosing one rule over its alternatives.)

+4
source

Although your example is very low (both expressions are in DNF), I can understand why someone imposed this policy.

Any normal form has the advantage that all expressions now have the same shape. In DNF, this form is a list of conditions / conditions, one of which must be true. In turn, paragraphs are lists of literals / conditions, each of which must be true.

DNF has the advantage that in most syntaxes it has a higher priority than or, and does not have an even higher priority, so DNF requires fewer brackets than CNF, and omitting the brackets is not an error.

+1
source

Many times, what coding standard you have is not as important as implementing them sequentially. Constantly written code greatly improves readability, and many times people who decide which one to choose use personal preferences rather than coding wisdom.

Assuming the standards you cited really help. I would say that most people do not understand that the && operator has higher operator accuracy than || therefore, using () around the && operator and operands helps make things more explicit.

Always remember that in many languages ​​both operands of a logical expression may not be executed if the value of the expression can be determined after evaluating only one of the operands. For instance:

1: (trueMethod () || falseMethod ())

2: (falseMethod () || trueMethod ())

If only one trueMethod () is executed. But in case 2, both methods are satisfied. Ordering can make a big difference.

+1
source

All Articles