forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComplexCondition.qhelp
More file actions
53 lines (37 loc) · 1.66 KB
/
ComplexCondition.qhelp
File metadata and controls
53 lines (37 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>In general, very complex conditions are difficult to write and read, and increase the chance
of defects.</p>
</overview>
<recommendation>
<p>Firstly, a condition can often be simplified by changing other parts of the
code to initialize variables more consistently. For example, is
there a semantic difference between <code>id</code> being <code>null</code> and
having zero-length? If not, choosing one sentinel value and using it
consistently simplifies most uses of that variable.</p>
<p>Secondly, extracting part of a condition into a Boolean-valued method can simplify the condition
and also allow code reuse, with all its benefits.</p>
<p>Thirdly, assigning each subcondition of the condition to a local variable, and then using the variables in
the condition instead can simplify the condition.</p>
</recommendation>
<example>
<p>The following example shows a complex condition found
in a real program used by millions of people. The condition is so confusing that even the programmer
who wrote it is not sure if he got it right (see the <code>TODO</code> comment).</p>
<sample src="ComplexCondition.java" />
<p>The condition can be simplified by extracting parts of the condition into Boolean-valued methods.
These methods are then used in the condition.</p>
<sample src="ComplexConditionGood.java" />
</example>
<references>
<li>
R. C. Martin, <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>, §17.G28. Prentice Hall, 2008.
</li>
<li>
S. McConnell, <em>Code Complete: A Practical Handbook of Software Construction</em>. Microsoft Press, 2004.
</li>
</references>
</qhelp>