I'm working with a model that currently looks like this:
class Sign {
enum Type { A, B }
Color color;
String textLine1;
String textLine2;
Type type;
Sign(Type type, Color color, String textLine1, String textLine2) { ... }
}
A sign of type A
has a color and 2 lines of text. A sign of type B
has a color and only 1 line of text. Therefore they're instantiated like so:
Sign signA = new Sign(A, someColor, "line1", "line2");
Sign signB = new Sign(B, someColor, "line1", null);
When working with these instances, code checks for the type
property and reads the appropriate fields.
I think this approach may be flawed as a B
sign should not expose properties it doesn't hold (line2). It's also unsightly to be passing null
to a bunch of properties it doesn't care about at instantiation time.
I'm wondering if it would be appropriate to use inheritance instead, where a base class would contain the shared fields and the type.
abstract class Sign {
enum Type { A, B }
Color color;
String textLine1;
Type type;
Sign(Type type, Color color, String textLine1) { ... }
}
class SignA extends Sign {
String textLine2;
SignA(Color color, String textLine1, String textLine2) {
super(A, color, textLine1);
this.textLine2 = textLine2;
}
}
class SignB extends Sign {
SignB(Color color, String textLine1) {
super(B, color, textLine1);
}
}
Is the above a recommended pattern for modeling models of this type? Note that these models have no behavior and are purely bags of properties.
textLine2
. So yes, a bunch of if statements. I was thinking that in my proposed approach I'd check the type enum, castSign
to one of the subtypes and work with that. I hadn't considered theinstanceof
usage.