-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathAbstractToConcreteCollection.qhelp
More file actions
59 lines (45 loc) · 2.05 KB
/
AbstractToConcreteCollection.qhelp
File metadata and controls
59 lines (45 loc) · 2.05 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
56
57
58
59
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Most collections in the Java standard library are defined by an abstract interface
(for example <code>java.util.List</code> or <code>java.util.Set</code>), which is
implemented by a range of concrete classes and a range of wrappers. Normally, except
when constructing an object, it is better to use the abstract types because this avoids
assumptions about what the implementation is.</p>
<p>A cast from an abstract to a concrete collection
makes the code brittle by ensuring it works only for one possible
implementation class and not others. Usually, such casts are
either an indication of over-reliance on concrete implementation types, or of the
fact that the wrong abstract type was used.</p>
</overview>
<recommendation>
<p>It is usually best to use the abstract type consistently in variable, field and parameter
declarations.</p>
<p>There may be individual exceptions. For example, it is common to declare variables
as <code>LinkedHashSet</code> rather than <code>Set</code> when the iteration order
matters and only the <code>LinkedHashSet</code> implementation provides the right
behavior.</p>
</recommendation>
<example>
<p>The following example illustrates a situation where the wrong abstract type is used.
The <code>List</code> interface does not provide a <code>poll</code> method, so
the original code casts <code>queue</code> down to the concrete type <code>LinkedList</code>, which
does. To avoid this downcasting, simply use the correct abstract type for this method, namely
<code>Queue</code>. This documents the intent of the programmer and allows for various implementations
of queues to be used by clients of this method.</p>
<sample src="AbstractToConcreteCollection.java" />
</example>
<references>
<li>
J. Bloch, <em>Effective Java (second edition)</em>,
Item 52.
Addison-Wesley, 2008.
</li>
<li>
Java API Specification:
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html">Collection</a>.
</li>
</references>
</qhelp>