开发者

Why is it important to express code in Disjunctive Normal Form?

At the company I work for, there has recently been a mandate that all 'highly visibile' boolean logic must be expressed in Disjunctive Normal Form.

So for instance (though the concept is language agnostic),

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

had to be replaced with:

#if defined(A) || (define开发者_高级运维d(C) && defined(D)) || defined(B)

What is the motivation for mandating that code has to be expressed in this manner? What are the advantages?


The advantage is that expressing such logic in a canonical/normalized form everywhere within a codebase will (theoretically) make it easier for programmers to understand and maintain it.

Without such a rule, some programmers are apt try to "optimize" an expression in such a way that it becomes difficult for a maintainer to unravel it. Also, a common form makes it easier to compose new expressions if that becomes necessary.

(These advantages are debatable. As with any stylistic guideline, having a consistent rule to follow is more important than the choice of one rule over its alternatives.)


Although your example is very poor (both expressions are in DNF), I can see why someone would impose this policy.

Any normal form has the advantage that all expressions now have the same form. In DNF, that form is a list of clauses/conditions, one of which has to be true. The clauses in turn are lists of literals/conditions, each of which has to be true.

DNF specifically has the advantage that in most syntaxes, and has higher precedence than or, and not has even higher precedence, so DNF requires fewer parentheses than CNF and omitting the parentheses is not an error.


Many times which coding standard you have isn't as important as consistently implementing them. Having consistently written code greatly increases readability and many times the people that decide which ones to pick are exercising personal preferences rather than coding wisdom.

Assuming that the standards you listed actually help. I'd say that most people don't realize off hand that the && operator has a higher operator precendence than || so using () around an && operator and operands helps make things more explicit.

Always remember that in many languages both operands of a boolean expression may not be executed if the value of the expression can be determined after evaluating just one of the operands. Such as:

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

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

In case one only trueMethod() is executed. But in Case 2 both methods are executed. Order can make a big difference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜