Search code examples
design-patternsrefactoringbuilder

Code refactoring - long base/super parameter list


These articles detail nicely how to fix long constructors

But what they don't say is how would we solve the issue with a long super() or base() call? ie

LongConstructorClass(string s1, string s2, string s3, string s4, string s5) { }

InheritsLongConstructorClass() : base("foo","bar","foo","bar","foo") { }

Basically it annoys me when I have multiple constructors and each of them have a long base() call.


Solution

  • The ParameterObject design pattern can be used to combine multiple parameter values into a single object. Consider a design like:

    public class MyClassOld { 
         MyClassOld(param1,param2,param3,param4) {...}  
    }
    

    Written as

    public class ParamObject {
        ParamObject(param1,param2,param3,param4) { }
    }
    
    public class MyClassNew {
        MyClassNew(ParamObject p) {}
    }
    
    public class MyChildClassNew {
        MyChildClassNew(ParamObject p) { super(p); }
    }
    

    Now you can add a builder pattern for ParamObject to make constructing ParamObject easier.