-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathStaticFieldWrittenByInstance.qhelp
More file actions
55 lines (41 loc) · 2.22 KB
/
StaticFieldWrittenByInstance.qhelp
File metadata and controls
55 lines (41 loc) · 2.22 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
54
55
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>A static field represents state shared between all instances of a particular
class. Typically, static methods are provided to manipulate this static state, and it
is bad practice to modify the static state of a class from an instance method
(or from a constructor).</p>
<p>There are several reasons why this is bad practice. It can be very difficult to
keep the static state consistent when there are multiple instances through which it
could be modified. Such modifications represent a readability issue:
most programmers would expect a static method to affect static state, and an instance
method to affect instance state.</p>
</overview>
<recommendation>
<p>If the field should be an instance field, ensure that it does not have a <code>static</code> modifier.</p>
<p>If the field does have to be static, evaluate the assumptions in the
code. Does the field really have to be modified directly in an instance method? It might be
better to access the field from within static methods, so that any concerns
about synchronization can be addressed without numerous synchronization statements in the code. Perhaps
the field modification is part of the static initialization of the class, and should be
moved to a static initializer or method.</p>
</recommendation>
<example>
<p>In the following example, a static field, <code>customers</code>, is written to by an instance method, <code>initialize</code>. It is entirely
reasonable for another developer to assume that an instance method called
<code>initialize</code> should be called on each new instance, and that is
what the code in <code>Department</code> does. Unfortunately, the static field is
shared between all instances of <code>Customer</code>, and so each time <code>initialize</code> is called,
the old state is lost.</p>
<sample src="StaticFieldWrittenByInstance.java" />
<p>The solution is to extract the static initialization of <code>customers</code> to a static method, where
it will happen exactly once.</p>
</example>
<references>
<li> Java Language Specification:
<a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.3.1.1">8.3.1.1 static Fields</a>.
</li>
</references>
</qhelp>