HTML and CSS Reference
In-Depth Information
1.5.2 Refactoring
To refactor code is to change its implementation while leaving its behavior intact. As
with unit tests, you have likely done it whether you called it refactoring or not. If you
ever extracted a helper method from one method to reuse it in other methods, you
have done refactoring. Renaming objects and functions is refactoring. Refactoring
is vital to growing your application while preserving a good design, keeping it DRY
(Don't Repeat Yourself) and being apt to adopt changing requirements.
The failure points in refactoring are many. If you're renaming a method, you
need to be sure all references to that method have changed. If you're copy-pasting
some code from a method into a shared helper, you need to pay attention to such
details as any local variables used in the original implementation.
In his book Refactoring: Improving the Design of Existing Code [1], Martin
Fowler describes the first step while refactoring the following way: “Build a solid
set of tests for the section of code to be changed.” Without tests you have no reliable
metric that can tell you whether or not the refactoring was successful, and that new
bugs weren't introduced. In the undying words of Hamlet D'Arcy, “don't touch
anything that doesn't have coverage. Otherwise, you're not refactoring; you're just
changing shit.”[2]
1.5.3 Cross-Browser Testing
As web developers we develop code that is expected to run on a vast combination of
platforms and user agents. Leveraging unit tests, we can greatly reduce the required
effort to verify that our code works in different environments.
Take our example of the strftime method. Testing it the ad hoc way involves
firing up a bunch of browsers, visiting a web page that uses the method and manually
verifying that the dates are displayed correctly. If we want to test closer to the code in
question, we might bring up the browser console as we did in Section 1.1, The Unit
Test , and perform some tests on the fly. Testing strftime using unit tests simply
requires us to run the unit test we already wrote in all the target environments.
Given a clever test runner with a bunch of user agents readily awaiting our tests,
this might be as simple as issuing a single command in a shell or hitting a button in
our integrated development environment (IDE).
1.5.4 Other Benefits
Well-written tests serve as good documentation of the underlying interfaces. Short
and focused unit tests can help new developers quickly get to know the system being
Search WWH ::

Custom Search