Is it okay to have type checking code when working with databases?

106 views Asked by At

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?

2

There are 2 answers

0
Nikos Tzianas On

I wouldn't suggest you to type check

The OOP way to solve this would be to make an insert method in the Metric class. Then override the method both in Rating and Quality with the appropriate code that inserts the object in the respective table.

for(Metric m : metrics) {
    int id = m.getId();
    m.insert();

}

Inside your loop simply call insert and due to late-binding the appropriate method will be called and the right code will be executed.

2
Karol Dowbecki On

You have encountered Object-relational impedance mismatch due to mapping between not fully compatible systems. Since inheritance is not possible between tables in the relational model you will have to sacrifice something in the object model that uses inheritance. There will be edge cases no matter what you do unless you switch to an object database.

If you define a custom CRUD operations in classes that extend Metric loading entites can be tricky. What exactly will be loaded by Metric.get(id) if each table has it's own PK sequence and both Rating and Quantity can have the same numeric PK value.

You can take a look on how JPA solves this problem. It uses custom annotations e.g. @MappedSuperclass and @Entity. I guess that's a form of type checking.