A great book to read is...

Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)
by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

Read more about this title...

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

"The first time you do something, you just do it. The second time you something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor."

Introduce Local Extension: A server class you are using needs several additional methods, but you can't modify the class.

Create a new class that contains these extra methods. Make this extension class a subclass or a wrapper of the original.

E.g From this...

 1 public interface IController{
 2         void Execute();
 3     }
 4     
 5     public class Controller : IController {
 6         protected void RenderView(string name, object data){
 7             //... note that this is a protected method
 8         }
 9         
10         public void Execute(){
11             //...
12         }
13     }

To this...

1 public interface IViewRenderer{
2         void Render<T>(string name, T data);
3     }
4     
5     public class LocalExtensionController : Controller, IViewRenderer {
6         public void Render<T>(string name, T data){
7             RenderView(name, data);
8         }
9     }

Replace Conditional with Polymorphism: You have a conditional that chooses different behavior depending on the type of an object.

Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract.

E.g From this...

 1 public class Bird{
 2         public Bird(BirdType type){
 3             _type = type;
 4         }
 5         
 6         public double GetSpeed(){
 7             switch(_type){
 8                 case BirdType.EUROPEAN:
 9                     return 5;
10                 
11                 case BirdType.AFRICAN:
12                     return 10;
13                     
14                 case BirdType.NORWEGIAN_BLUE:
15                     return 20;
16             }
17             throw new ArgumentException();
18         }
19         
20         private BirdType _type;        
21     }
22     
23     public enum BirdType{
24         EUROPEAN,
25         AFRICAN,
26         NORWEGIAN_BLUE
27     }

To this...

 1 public interface IBird{
 2         double GetSpeed();
 3     }
 4     
 5     public class EuropeanBird : IBird {
 6         public double GetSpeed(){
 7             return 5;
 8         }
 9     }
10 
11     public class AfricanBird : IBird {
12         public double GetSpeed() {
13             return 10;
14         }
15     }
16 
17     public class NorwegianBlueBird : IBird {
18         public double GetSpeed() {
19             return 20;
20         }
21     }
comments powered by Disqus