Reputation: 278
I'll speak a little abstractly to make the problem statement brief and succinct. For all purposes, let's assume .NET/C# as the underlying technology/language.
Let's say you're writing a software program and designing some class/type to represent some entity of interest. You find out that this entity has some sort of a lifecycle with different states. As instances of this entity transition from one state to another, they gain certain attributes/properties but lose others.
Now if you're designing a class/type to represent such entity, one design choice would be to introduce one all-encompassing class type that includes a superset of all possible properties of the entity throughout its lifecycle.
Another choice would be to introduce some sort of a type hierarchy where you represent the entity of interest using different types each of which represents it in a particular state.
Now my questions are:
Generally speaking, how can one decide whether representing different states/aspects of an entity is better accomplished using properties/attributes on a single type vs. different types?
If you choose to represent your entity using multiple types:
a. How would you tackle cases where certain properties of this entity are present/defined in multiple states?
b. What if your entity is persisted/serialized using JSON for instance? How would you be able to serialize it and deserialize it given all the different types representing different states?
Upvotes: 0
Views: 238
Reputation: 36118
Both your solutions are not particular good. What you really want are algebraic datatypes, a.k.a. disjoint or discriminated unions. Unfortunately, most old-school OO languages don't have those. In the .NET ecosystem, it's mainly F# that has proper support for them. See e.g. here or here for a brief introduction.
Upvotes: 2
Reputation:
If you need to use multiple types, you could promote and demote instances from one type to another by copy-constructing them or using a factory to create instances of the new type.
But, I would not rely on type hierarchy alone, as internal state is unavoidable in a state machine.
Upvotes: 0
Reputation: 1475
You might want to consider basing such an object around the .net ExpandoObject (MSDN link) - you can dynamically add / remove properties to it and query whether it has a given property. This gives you more flexibility than trying to create an entire (static) hierarchy up front.
Upvotes: 0