Java Reference
In-Depth Information
4.1.4
Refactoring with confidence
Without unit tests, it's difficult to justify refactoring, because there's always a relatively
high risk that you may break something. Why would you chance spending hours of
debugging time (and putting the delivery at risk) only to improve the implementation
or change a method name? Unit tests provide the safety net that gives you the confi-
dence to refactor.
Let's move on with our implementation and try to improve it further.
JUnit best practice: refactor
Throughout the history of computer science, many great teachers have advocated
iterative development. Niklaus Wirth, for example, who gave us the now-ancient
languages Algol and Pascal, championed techniques like stepwise refinement .
For a time, these techniques seemed difficult to apply to larger, layered appli-
cations. Small changes can reverberate throughout a system. Project manag-
ers looked to up-front planning as a way to minimize change, but productivity
remained low.
The rise of the xUnit framework has fueled the popularity of agile methodologies
that once again advocate iterative development. Agile methodologists favor writ-
ing code in vertical slices to produce a working use case, as opposed to writing
code in horizontal slices to provide services layer by layer.
When you design and write code for a single use case or functional chain, your
design may be adequate for this feature, but it may not be adequate for the next
feature. To retain a design across features, agile methodologies encourage refac-
toring to adapt the code base as needed.
But how do you ensure that refactoring, or improving the design of existing code,
doesn't break the existing code? This answer is that unit tests tell you when and
where code breaks. In short, unit tests give you the confidence to refactor.
The agile methodologies try to lower project risks by providing the ability to cope
with change. They allow and embrace change by standardizing on quick iterations
and applying principles like YAGNI (You Ain't Gonna Need It) and The Simplest
Thing That Could Possibly Work . But the foundation on which all these principles
rest is a solid bed of unit tests.
4.1.5
Improving implementation
Unit tests are a first-rate client of the code they test. They force the API under test to
be flexible and to be unit testable in isolation. You usually have to refactor your code
under test to make it unit testable (or use the TDD approach, which by definition
spawns code that can be unit tested; see the next chapter).
It's important to monitor your unit tests as you create and modify them. If a unit
test is too long and unwieldy, it usually means the code under test has a design smell
and you should refactor it. You may also be testing too many features in one test
 
 
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search