Java Reference
In-Depth Information
The example is inflexible because it hardwires the
ArrayList
class into multiple
locations. This hardwiring focuses the developer into thinking specifically about array
lists instead of generically about lists.
Lackoffocusisproblematicwhenarequirementschange,orperhapsaperformance
issuebroughtaboutby
profiling
(analyzingarunningapplicationtocheckitsperform-
ance), suggests that the developer should have used
LinkedList
.
Theexampleonlyrequiresaminimalnumberofchangestosatisfythenewrequire-
ment.Incontrast,alargercodebasemightneedmanymorechanges.Althoughyouonly
needtochange
ArrayList
to
LinkedList
,tosatisfythecompiler,considerchan-
ging
arrayList
to
linkedList
, to keep
semantics
(meaning) clear—you might
have to change multiple occurrences of names that refer to an
ArrayList
instance
throughout the source code.
The developer is bound to lose time while refactoring the code to adapt to
LinkedList
. Instead, the developer could have saved time by writing this example
tousetheequivalentofconstants.Inotherwords,theexamplecouldhavebeenwritten
torelyoninterfaces,andtoonlyspecify
ArrayList
inoneplace.Thefollowingex-
ample shows you what the resulting code would look like:
List<String> list = new ArrayList<String>();
void dump(List<String> list)
{
// suitable code to dump out the list
}
Thisexampleismuchmoreflexiblethanthepreviousexample.Ifarequirementsor
profiling change suggests that
LinkedList
should be used instead of
ArrayList
,
simplyreplace
Array
with
Linked
andyouaredone.Youdonotevenhavetochange
the parameter name.
INTERFACES VERSUS ABSTRACT CLASSES
Javaprovidesinterfacesandabstractclassesfordescribing
abstract types
(typesthat
cannot be instantiated). Abstract types represent abstract concepts (drawable and
shape, for example), and instances of such types would be meaningless.
Interfaces promote flexibility through lack of implementation—
Drawable
and
List
illustratethisflexibility.Theyarenottiedtoanysingleclasshierarchy,butcan
be implemented by any class in any hierarchy.