Java Reference
In-Depth Information
that case, every method that gets executed inside that static method becomes hard
to test.
Static code and the inability to use polymorphism in your application affect your
application and tests equally. No polymorphism means no code reuse for both
your application and your tests. This can lead to code duplication in the applica-
tion and tests, something we try to avoid.
5.2.8
Favor composition over inheritance
Many people choose inheritance as a code-reuse mechanism. We think composition
can be easier to test. At runtime, code can't change an inheritance hierarchy, but we
can compose objects differently. We strive to make our code as flexible as possible at
runtime. This way we can be sure that it's easy to switch from one state of our objects
to another, and that makes our code easily testable.
For example, because we consider it bad practice for all servlets to extend
AuthenticatedServlet
, we always need to instantiate the credentials for a test user
in our tests. On the other hand, we could add a
Credentials
instance variable to
those servlets that need it and make our classes easier to test by instantiating the
Credentials
variable only when we need it.
5.2.9
Favor polymorphism over conditionals
As mentioned previously, we do only the following in our tests:
Instantiate the class to test
■
Set the class into a particular state
■
Assert the final state of the class
■
Difficulties may arise at any of these points. For example, it could be difficult to instan-
tiate our class if it's too complex.
One of the main ways to decrease complexity is to try to avoid long
switch
and
if
statements. Consider listing 5.6.
Listing 5.6
Example of a bad design with conditionals
public class
DocumentPrinter {
[...]
public void
printDocument() {
switch
(document.getDocumentType()) {
case
Documents.WORD_DOCUMENT:
printWORDDocument();
break
;
case
Documents.PDF_DOCUMENT:
printPDFDocument();
break
;
case
Documents.TEXT_DOCUMENT:
printTextDocument();
break
;