HTML and CSS Reference
In-Depth Information Passing the Test for String.prototype.trim
As an example of the simplest solution that could possibly work, Listing 2.2 shows
the sufficient amount of code to pass the test in Listing 2.1. It caters only to the
case stated in that original test, leaving the rest of the requirements for following
Listing 2.2 Providing a String.prototype.trim method
String.prototype.trim = function () {
return this.replace(/^\s+/, "");
The keen reader will probably spot several shortcomings in this method, in-
cluding overwriting native implementations and only trimming left side white space.
Once we are more confident in the process and the code we are writing, we can take
bigger steps, but it's comforting to know that test-driven development allows for
such small steps. Small steps can be an incredible boon when treading unfamiliar
ground, when working with error prone methods, or when dealing with code that
is highly unstable across browsers. The Simplest Solution that Could Possibly Work
The simplest solution that could possibly work will sometimes be to hard-code
values into production code. In cases where the generalized implementation is not
immediately obvious, this can help move on quickly. However, for each test we
should come up with some production code that signifies progress. In other words,
although the simplest solution that could possibly work will sometimes be hard-
coding values once, twice and maybe even three times, simply hard-coding a locked
set of input/output does not signify progress. Hard-coding can form useful scaf-
folding to move on quickly, but the goal is to efficiently produce quality code, so
generalizations are unavoidable.
The fact that TDD says it is OK to hard-code is something that worries a lot
of developers unfamiliar with the technique. This should not at all be alarming so
long as the technique is fully understood. TDD does not tell us to ship hard-coded
solutions, but it allows them as an intermediary solution to keep the pace rather than
spending too much time forcing a more generalized solution when we can see none.
While reviewing the progress so far and performing refactoring, better solutions
may jump out at us. When they don't, adding more use cases usually helps us pick
up an underlying pattern. We will see examples of using hard coded solutions to
keep up the pace in Part III, Real-World Test-Driven Development in JavaScript.
Search WWH ::

Custom Search