During coding I frequently encounter this situation:
- I have several objects (
ConcreteType1,ConcreteType2, …) with the same base typeAbstractType, which has abstract methodssaveandload. Each object can (and has to) save some specific kind of data, by overriding thesavemethod. - I have a list of
AbstractTypeobjects which contains variousConcreteTypeXobjects. - I walk the list and the
savemethod for each object.
At this point I think it’s a good OO design. (Or am I wrong?) The problems start when I want to reload the data:
Each object can load its own data, but I have to know the concrete type in advance, so I can instantiate the right ConcreteTypeX and call the load method. So the loading method has to know a great deal about the concrete types. I usually ‘solved’ this problem by writing some kind of marker before calling save, which is used by the loader to determine the right ConcreteTypeX.
I always had/have a bad feeling about this. It feels like some kind of anti-pattern…
Are there better ways?
EDIT: I’m sorry for the confusion, I re-wrote some of the text. I’m aware of serialization and perhaps there is some next-to-perfect solution in Java/.NET/yourFavoriteLanguage, but I’m searching for a general solution, which might be better and more ‘OOP-ish’ compared to my concept.
If you can’t simply use serialization, then I would still definitely pull the object loading logic out of the base class. Your instinct is correct, leading you to correctly identify a code smell. The base class shouldn’t need to change when you change or add derived classes.
The problem is, something has to load the data and instantiate those objects. This sounds like a job for the Abstract Factory pattern.