-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathMagicConstantsNumbers.qhelp
More file actions
53 lines (39 loc) · 1.48 KB
/
MagicConstantsNumbers.qhelp
File metadata and controls
53 lines (39 loc) · 1.48 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>A <em>magic number</em> is a numeric literal (for example, <code>8080</code>,
<code>2048</code>) that is used in the middle of a block of code without
explanation. It is considered bad practice to use magic numbers because:</p>
<ul>
<li>A number in isolation can be difficult for other programmers to understand.
</li>
<li>It can be difficult to update the code if the requirements change. For example, if the magic
number represents the number of guests allowed, adding one more guest means that you must change
every occurrence of the magic number.
</li>
</ul>
</overview>
<recommendation>
<p>Assign the magic number to a new named constant, and use this instead. This overcomes the two problems
with magic numbers:</p>
<ul>
<li>A named constant (such as <code>MAX_GUESTS</code>) is more easily understood by other programmers.
</li>
<li>Using the same named constant in many places makes the code much easier to
update if the requirements change, because you have to update the number in only one place.
</li>
</ul>
</recommendation>
<example>
<p>The following example shows a magic number <code>timeout</code>. This should be replaced by a new
named constant, as shown in the fixed version.</p>
<sample src="MagicConstantsNumbers.java" />
</example>
<references>
<li>
R. C. Martin, <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>, §17.G25. Prentice Hall, 2008.
</li>
</references>
</qhelp>