Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 773
jax Avatar asked Jul 04 '26 15:07

jax


2 Answers

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.

like image 178
Karol Dowbecki Avatar answered Jul 06 '26 05:07

Karol Dowbecki


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.

like image 29
Nikos Tzianas Avatar answered Jul 06 '26 05:07

Nikos Tzianas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!