Is there a general best practice when to use inheritance:
public class Information {
private String text;
}
public class Message extends Information {
}
public class Faq extends Information {
}
public class News extends Information {
}
and when to use enum as a member variable to distinguish:
public enum InformationType {
MESSAGE, FAQ, NEWS
}
public class Information {
private String text;
private InformationType type;
}
In the code that I work with I have the second - a type field and what bothers me is the code
public void displayInformation(final Information information) {
if (information.getType == InformationType.MESSAGE) {
....
} else if (information.getType == InformationType.FAQ) {
....
} else if (information.getType == InformationType.NEWS) {
....
} else {
// some error handling
}
}
This is definitely a code smell and I don't see how you can have the enum as member variable and not have these if-elses!? If that is true, then you should never have enums as types for the objects, but I see this "pattern" so often!
Aucun commentaire:
Enregistrer un commentaire