Nuds Nuds - 2 months ago 7
C# Question

Basic inheritance - too verbose?

I'm looking for a programmatically smarter way to inherit here. I'm very new to the world of programming so it's more of methodology I'm looking for here. Is this the right way to inherit?

The base class in this case has a large constructor. Having to call

base(w, x, y, z)
in each inherited class looks incredibly verbose. Quite frankly, it looks like lazy or bad code.

public class DataStudioGear : DataItem {
string name;

int moneyValue;
int compression;
int wideness;
int wowFactor;

public DataStudioGear(string name, int value, int comp, int wide, int wow) {
this.name = name;
moneyValue = value;
compression = comp;
wideness = wide;
wowFactor = wow;
}
}


So now any class that inherits from this has to of course, pass those variables along to the constructor. That leaves me with a bunch of classes that look like this:

public class Console : DataStudioGear {
public Console(string name, int value, int comp, int wide, int wow) : base(name, value, comp, wide, wow) {

}
}

public class Compressor : DataStudioGear {
public Compressor(string name, int value, int comp, int wide, int wow) : base(name, value, comp, wide, wow) {

}
}


These constructors are huge. Although I'm very new to programming in general, it just looks like bad code.

Is there a better solution for what I'm trying to accomplish here?

Answer

Consider using the factory pattern

public class DataStudioGear : DataItem
{
    string _name;
    private int _moneyValue;
    int _compression;
    int _wideness;
    int _wowFactor;

    public static T DataTestFactory<T>(string name, int value, int comp, int wide, int wow)
        where T : DataStudioGear, new()
    {
        return new T { _name = name, _moneyValue = value, _compression = comp, _wideness = wide, _wowFactor = wow};
    }
}

public class Console : DataStudioGear { }

public class Compressor : DataStudioGear { }

[TestMethod]
public void TestDataItemFactory()
{
    Console console = DataStudioGear.DataTestFactory<Console>("test", 1, 1, 1, 1);
    Compressor compressor = DataStudioGear.DataTestFactory<Compressor>("test", 1, 1, 1, 1);
}