geek yapping

Twitter












Chain Constructors

Chain Constructors is another refactoring from the book Refactoring to Patterns, it helps remove duplication in constructor overloads. This should be a very familiar refactoring for most developers. Catch all constructors are produced, and hopefully minimized, that other constructors rely on either directly or indirectly. Mechanics
  1. Study the constructors in the class and find the two with the most shared code. Say I have two constructors to create lines as follows:
    public class Line
    {
    	...
    	private Line()
    	{
    		Style = LineStyle.Solid;
    		Color = LineColor.Black;
    		Thickness = 1;
    	}
    
    	private Line(LineStyle style, LineColor color, int thickness)
    	{
    		Style = style;
    		Color = color;
    		Thickness = thickness;
    	}
    	...
    }
    
    These can be chained together, to reduce redundant code and leave a common spot for future property initializations.
    public class Line
    {
    	...
    	private Line()
    		: this(LineStyle.Solid, LineColor.Black, 1)
    	{
    	}
    
    	private Line(LineStyle style, LineColor color, int thickness)
    	{
    		Style = style;
    		Color = color;
    		Thickness = thickness;
    	}
    	...
    }
    
  2. Repeat step one, even with constructors already chained, to maximize chaining and code re-use.
  3. Re-scope any constructors that no longer need to be public.
Pros
  1. Code reuse
  2. Avoid future mistakes when new code in one constructor isn’t copied to others.
Cons
  1. Highly nested constructors might become confusing, try to keep it simple, if you find many levels of chaining, you may want to consider applying refactorings to or twoards Creation Method and/or Factory patterns to help reduce ambiguity


Feedback

No comments posted yet.