Question

Is there some specific piece of advice around persist values that indicate type? Specifically I want to know if I should persist a flag/state indicating the type in persistence or not. I get the feeling I'm forgetting/not understanding some core concept of OO or data modelling.

Something that's been on my mind for the last while is to consider when to use flags and when not to, and intermixing this idea of recreating objects of some certain type out of persistence.

The reason for my concern over flags is that in the software I often create (in-house created corporate software developed with Java), these flags become pieces of information which are hard to maintain and which subsequent developers need to be aware of in order to maintain them (perhaps creating code bloat).

So, when I persist my foo, should I persist with it some flag that indicates whether it is a foobar or a foobo? Is there specific advice about this, some gap in my OO-foo or data modelling that I'm forgetting?

Was it helpful?

Solution

It depends on where you persist and what you persist. It would make sense to use some enums when wanting to persist a class hierarchy and you want to persist all the elements of the class hierarchy in a single place.

Take for example mapping inheritance to a single table in and ORM (e.g. @Inheritance(strategy = InheritanceType.SINGLE_TABLE in JPA). Say you have a superclass User and two subclasses CustomerUser and AdminUsers and you want them mapped to a single column users. Here you need a discriminator column to differentiate between possible user types; this column is better a string or an enum rather than a flag. This column should have the value customer for entries that represent CustomerUser and admin for entries that represent AdminUser.

But if you do not have some common elements from distinct classes that have a common superclass, then it doesn't make sense to specify the type when you persist it. You should know from the context/metadata what the type is (be it a column name in a relational database, a name of the file, a tag name in a XML etc.) and you shouldn't strongly couple it with your application model because you may want other applications reading the persisted data. Given the above example you might as well have two distinct columns admin_users and customer_users and then there is no need for persisting the type.

Licensed under: CC-BY-SA with attribution
scroll top