Friday, May 08, 2009

Refactoring to Patterns

A refactoring is a “behavior-preserve transformation” or, as Martin Fowler defines it, “a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior ”

The process of refactoring involves the removal of duplication, the simplification of complex logic, and the clarification of unclear code. When you refactor, you relentlessly poke and proud your code to improve its design. Such improvements may involve something as small as changing a variable name or as large as unifying two hierarchies.

To refactor safely, you must either manually test that your changes didn't break anything or run automated test. You will have more courage to refactor and be more willing to try experimental designs if you can quickly run automated test to confirm that your code still works.

What motivate Us to refactor?
Make easier to add new code
Improve the design of existing code
Gain a better understanding of code
Make coding less

Ward Cunningham recommends write human readable code, which means write code as like spoken language and separates important code from distracting code. And Martin Fowler said: Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Keep code clean, is a lot like keeping a room clean. Once your room becomes a mess, it becomes harder to clean. The worse the mess becomes, the less you want to clean it.

Make little steps, in order to refactor a large piece of code you should start by get baby steps, like rename a variable or eliminate some duplicate code, besides is a good idea to start with test in order to prove that your changes don't change any behavior. Life cycle of test is: red, green, refactor. Which means using Junit you have to write test first (red) that guide you to the functionality and then you can create functionality(green) and finally you'll be able to start some refactor.

Composite refactorings are high-level refactorings composed of low-level refactorings. Much of the work performed by low-level refactorings involves moving code around. For example, extract method, moves code to a new method, pull up method, move method from a subclass to a superclass, extract class, moves code to a new class, and move method from the one class to another.

Substitute Algorithm, is a good example to refactoring that is best implemented using test-driven refactorings. It's essentially involves completely changing an existing algorithm for one that is simpler and clearer.

Refactoring to patterns

No comments: