Think back, if you will, to how we built this method. Originally it was written inline in the OnKeyDown method of the Form. It was pretty ugly then, and we put all those comments in it hoping to make it better. Then, in a few short sessions ”none of them over two hours ”we cleaned it up, using these techniques:
Extract Class ”to create the TextModel class.
Extract Method ”to give good names to the loops that copied and added.
Extract Method ”was also used to clean up a few other things.
Substitute Algorithm ”to move to ArrayList, and again to get rid of newline.
Replace Magic Number with Symbolic Constant ”to move the return and paragraph tag out of the mainline.
And probably more. Each change was pretty simple, and almost all of them worked the first time. The resulting code is much improved.
It is possible to imagine having done better with forethought. Hindsight is like that. What we d like you to take away from this experience is that ”believe us ”it almost always works out this way. We begin with simple, straightforward, almost procedural code. At this point we re working to understand how to do the thing at all. We usually write more tests up front, as you ll see in later chapters, and we usually express intention a bit more than we did here. But we always wind up with code that wants a bit of refactoring to be really nice. And the refactoring always goes like it did this time: one little step after another, each one going along quite well. Once in a while, a refactoring won t work or will be a bad idea. Since it s a small step, we just back it out.
We ve been working on this application only a couple of hours at a time. There isn t much time in it at all, and it s looking pretty good!
This style of programming works better for us ”and for most people who try it ”than doing a whole lot of design up front and trying to get it all right the first time. The lesson to take home is that this approach is worth trying. Push it as far as you can, especially when you re doing things where you re comfortable. We think you ll find that the optimal point has far less up-front design than you would expect and that the whole process is easy and stress-free.