Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to save and load different types of objects?
    text
    copied!<p>During coding I frequently encounter this situation:</p> <ol> <li>I have several objects (<code>ConcreteType1</code>, <code>ConcreteType2</code>, ...) with the same base type <code>AbstractType</code>, which has abstract methods <code>save</code> and <code>load</code> . Each object can (and has to) save some specific kind of data, by overriding the <code>save</code> method. </li> <li>I have a list of <code>AbstractType</code> objects which contains various <code>ConcreteTypeX</code> objects.</li> <li>I walk the list and the <code>save</code> method for each object.</li> </ol> <p>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:</p> <p>Each object can load its own data, but I have to know the concrete type in advance, so I can instantiate the right <code>ConcreteTypeX</code> and call the <code>load</code> 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 <code>save</code>, which is used by the loader to determine the right <code>ConcreteTypeX</code>.</p> <p>I always had/have a bad feeling about this. It feels like some kind of anti-pattern...</p> <p>Are there better ways?</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload