Let’s have a library of objects Person, Cat, Dog, Pencil and Byke.
Let’s give to Person a FavoriteThing member, that can be of any of listed types.
Let’s imagine that we have to save the Person’s state using a serialization, so we make all of listed objects as Serializable.
How do we now protect the Person from “injecting” him a “FavoriteThing” like Cobra class, that does not comply the requirements (to be Serializable, or others, like to be inoffensive :).
You might want to write a
FavoriteThingtype which acts as a tagged union. In other words, it has a property for each type (person, cat etc) but enforces that it only contains one value at a time. You may not explicitly need a tag field if these are all reference types; just make sure that only one of your strongly-typed fields is non-null at a time. You will need to provide a way of determining which type has a value though.Another option is to make all of those types implement a common interface – but that may not be an appropriate design, if those types shouldn’t really know about the “favorite” concept.
It’s hard to be more concrete without knowing what you’d want to do with the favorite thing…