So with inheritance I always find my self dealing with extremely long constructors in the most specific classes. I am looking for a paradigm or method by which I can avoid this problem. I’ve thought of using factories, but if I did, I would still have to use the constructor in the factory. Regardless of that thought, is there anything I can do to keep constructor parameter length down?
For example:
abstract class DrawableComponent : Component, ITransformable, IScalable, IDrawable, IRotatable
Is a child class with a constructor like
DrawableComponent(string Name, int SizeX, int SizeY, int X, int Y, float Rotation) : base(Name) { ... }
Now let’s say I’d like to make a child of that. Things just get more complex and ugly.
class TextBoxComponent : DrawableComponent, IRenderable
The constructor now gets extremely long:
public TextBoxComponent(
IDrawableUnit Background,
IDrawableUnit Text,
string Name,
int X,
int Y,
int SX,
int SY)
: base(Name, SX,SY,X,Y,0.0f)
{
this.Background = Background;
this.Foreground = Foreground;
}
In summary of this, I’m sick of having things like this:
class Blah {Blah(blah)}
class childBlah : Blah {childBlah(blah,blahs,blaha) : base (blah)}
class grandChildBlah : childBlah {grandChildBlah(blah, blahs, blaha, blaht, blauh) : base(blah,blahs,blaha) }
If you have really long constructor parameter lists, then you must have many fields in a single class? This indicates that you should think about splitting those classes into more than one class, or extracting groups of related fields into their own types.
For example, x and y coordinate fields or width and height values:
should really be a single point or vector or rectangle object:
Another suggestion might be to reduce your inheritance, and instead use composition. Instead of an is-a relationship, use a has-a relationship:
Your ‘blah’ example then becomes something like: