Design Problems
-
Creating Objects
-
How can an object be created
so that subclasses can redefine which class to instantiate?
-
How can a class defer instantiation to subclasses?
-
Flexible Alternative to Constructors
-
How can a flexible alternative be provided to
direct constructor calls?
Refactoring Problems
-
Unclear Code
-
How can multiple constructors of a class that differ
only in their arguments
be named differently to avoid unclear code?
[BGI]
Replace Constructors with Creation Methods (57)
[JK05]
Background Information
-
Inflexible constructor names can cause unclear code.
-
In most languages, the constructor of a class
must be named after the class.
If a class has multiple constructors,
they all must have the same name, which makes it hard
to distinguish them and call the right one.
-
Factory methods can be named freely to
clearly communicate their intent.
-
"Consider static factory methods instead of constructors."
[JB08, Item 1]
See also Implementation.
-
Refactoring and "Bad Smells in Code"
[MF99]
[JK05]
-
Code smells
are certain structures in the code that "smell bad" and
indicate problems that can be solved by a refactoring.
-
The most common code smells are:
complicated code
(including complicated/growing conditional code),
duplicated code,
inflexible code
(that must be changed whenever requirements change), and
unclear code
(that doesn't clearly communicate its intent).