- Home /
class design preference
If you were designing a class that could be used for a few different types of objects, and not every property was used for every object type how would you do it between the two versions here?
Mainly, sometimes an object will always only have one "transition" value, and sometimes it will have more than one. Would you use an array even for object that only need one value, or would you use a single property for those and an array for objects that need more than one value?
class myClass
{
public string transition; // Use for objects that only need one value.
public string[] transitions; // Ignore for objects that only need one value.
public int otherProperty;
...etc.
}
or
{
public string[] transitions; // Use when one or more values are needed.
public int otherProperty;
...etc.
}
Answer by testure · Jun 29, 2011 at 05:17 PM
Personally, I just define it as an array. it's just cleaner that way. If you're juggling two variables, you're always going to end up with a check to see if transitions is null or empty before falling back to the singular variable- so it just seems like a lot of extra wasted work that makes things overly convoluted.
To me it's much easier to just initialize an array with one index and have all of my logic code remain the same.. less margin for error and it's easier to read.
Thanks for the answer. I would like to hear from several more people too, whether you agree or disagree with testure's answer.
Testure is right, having variables which may or may not be relevant is bad design. Every variable in scope should mean something, polymorphism via 'if' statements is an anti-pattern to be avoided.