I'm trying to insert some code into a database. But, i have encountered a problem while working with models that are subclasses of each other. I have a list that holds all these subclases.
List<Metric> metrics = experiment.getMetrics();
for(Metric m : metrics) {
int id = m.getId();
// type checking code
}
Metric has sublcases of Rating and Quantity. Each of these in turn have there own uniquely defined tables. I am conflicted over the idea of using type checking. But I don't see any immediate solution. One alternative, which doesn't seem any better, would be to create a new column in the Metric table called metric_type. But this would lead to something quite similar to type checking. Any suggestions?
I wouldn't suggest you to type check
The OOP way to solve this would be to make an
insert
method in theMetric
class. Then override the method both inRating
andQuality
with the appropriate code that inserts the object in the respective table.Inside your loop simply call
insert
and due to late-binding the appropriate method will be called and the right code will be executed.