Java Reference
In-Depth Information
default :
printBinaryDocument();
break ;
}
}
[...]
}
This implementation is awful for several reasons. This code is hard to test and
maintain. Every time we want to add a new document type, we add additional case
clauses. If that happens often in your code, you'll have to change it in every place
that it occurs.
Every time you see a long conditional statement, think of polymorphism. Polymor-
phism is a natural object-oriented way to avoid long conditionals, by breaking a class
into several smaller classes. Several smaller components are easier to test than one
large complex component.
In the given example, we can avoid the conditional by creating different document
types like WordDocument , PDFDocument , and XMLDocument , each one implementing a
printDocument() method. This will decrease the complexity of our code and will
make it easier to read.
5.3
Test-driven development
In chapter 3, we designed an application controller and quickly wrote some tests to
validate your design. As we wrote the tests, the tests helped improve the initial design.
As you write more unit tests, positive reinforcement encourages you to write them ear-
lier. As you design and implement, it becomes natural to wonder about how you'll test
a class. Following this methodology, more developers are making the leap from test-
friendly designs to test-driven development.
DEFINITION Test-driven development ( TDD ) is a programming practice that
instructs developers to write new code only if an automated test has failed and
to eliminate duplication. The goal of TDD is “clean code that works.”
Let's move on and see how we can adapt our development lifecycle to enforce the test-
driven development approach.
5.3.1
Adapting the development cycle
When you develop code, you design an application programming interface ( API ) and
then implement the behavior promised by the interface. When you unit test code, you
verify the promised behavior through a method's API . The test is a client of the
method's API , just as your domain code is a client of the method's API .
The conventional development cycle goes something like this: code, test , (repeat),
commit. Developers practicing TDD make a seemingly slight but surprisingly effective
adjustment: test , code, (repeat), commit. (More on this later.) The test drives the
design and becomes the method's first client.
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search