New Perspectives On Web Design

(C. Jardin) #1
By Nicholas Zakas CHAPTER 2

The combination of code comments and tests helps to bring legacy
code under control. Even though progress will seem slow by adding one
test at a time, having one test is better than having no tests. Having two
tests is better than having one. As you continue to work with the code and
continue to add tests, you’ll expose more and more functionality to the
light of day. Parts of the legacy code will start to make sense because you
have simple ways of determining if the code is functioning properly. It’s
important to think of running a marathon rather than a sprint. You can’t
write all the tests at once, but as long as you continue down the path of
writing tests, you’ll eventually reach a much better understanding of the
legacy code.


RefaCToRing anD RewRiTing


If you are lucky, you may actually get some time to refactor or rewrite
legacy code. Refactoring involves leaving the public interface of an API
unchanged while changing the underlying implementation. This is where
effective unit tests are extremely important. Good unit tests exercise the
public interface without regard for implementation details. In short, unit
tests are designed to test interfaces by asserting that certain inputs result
in certain outputs. Outputs can be return values, changes to existing ob-
jects, errors that are thrown, or any other visible effect of executing some
code. It is impossible to effectively refactor code unless you have unit tests
in place to verify that your changes result in the same outcomes as the old
code.
Rewriting code is when you make significant changes to both the
public interface and the implementation. This is a developer’s dream: you
have free reign to start from scratch and make something better than what
you’ve been working with. When rewriting code, it doesn’t matter what
you replace because you are creating something new. Unfortunately, this is
usually the time when the least future-friendly code gets written.

Free download pdf