0

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
wonton
  • 7,568
  • 9
  • 56
  • 93

1 Answers1

2

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.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
  • yep I realize that, but note that InheritsLongConstructorClass does not take any parameters, it's hard set to the values stated in base(). there's no way to declare a ParameterObject and pass it to base without passing it to InheritsLongConstructorClass() first – wonton Jun 26 '13 at 22:08
  • I think the best you can do in this case is to create a `ParameterObject` to encompass the values for `LongConstructorClass`. At least now you would be limiting the messiness to `InheritsLongConstrutorClass`. You could then call `base(new ParameterObject().p1(..).p2(..).build())`...or if you're able to modify those classes then you can do more with the parameter object pattern – Jeff Storey Jun 26 '13 at 22:11
  • Agreed, I think you should have a look at your actual use case. Can you identify one or more concepts by which your parameters can be grouped together? You don't have to stick with one parameter object. As [sourcemaking.com](http://sourcemaking.com/refactoring/introduce-parameter-object) says: "Often you see a particular group of parameters that tend to be passed together. Several methods may use this group, either on one class or in several classes" – mdo Jun 28 '13 at 09:46