Refactoring: Improving the design of existing code(To be continued)


When you find you have to add a feature to a program, and the program’s code is not
structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature.

Before you start refactoring, check that you have a solid suite of tests. These tests
must be self-checking.

Smaller pieces of code tend to make things more manageable.

first step is to find a logical clump of code and use Extract Method;

Refactoring changes the programs in small steps. If you make a mistake, it is easy to
find the bug.


Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

In most cases a method should be on the object whose data it uses, thus the method should be moved. To do this I use Move Method. With this you first copy the code over, adjust it to fit in its new home, and compile. The next step is to find every reference to the old method and adjust the reference to use the new method. The next thing is to remove the old method. The compiler should tell me whether I missed anything. I then test to see if I’ve broken anything

Replace Temp with Query

I like to get rid of temporary variables such as this as much as possible. Temps are often a problem in that they cause a lot of parameters to be passed around when they don’t have to be. If the calculation will be performed multiple times, do the optimization in the calculation class.

The other concern with this refactoring lies in performance. Don’t worry about this while refactoring. When you optimize you will have to worry about it, but you will then be in a much better position to do something about it, and you will have more options to optimize effectively

It is a bad idea to do a switch based on an attribute of another object. If you must use a switch statement, it should be on your own data, not on someone else’s.