Note that there are some explanatory texts on larger screens.

plurals
  1. POHow should I design this code (parallel class hierarchies)?
    primarykey
    data
    text
    <p>I have a set of apps that all need to synchronize with a webservice:</p> <ol> <li>download some XML from a webservice.</li> <li>parse that XML.</li> <li>then update the database to match the parsed XML.</li> </ol> <p>I'd like to keep as much of the relevant code as possible in a common library to avoid duplication, and I'd like to have the different apps all slot their parsing and updating code into a fairly simple common framework.</p> <p>So there's a common sync() method:</p> <pre><code>public void sync(URI updateUrl, XMLParser parser, Updater animalUpdater) { String raw = getXML(); List&lt;ParsedAnimal&gt; parsed = parser.parse(raw); // try: // begin transaction for (ParsedAnimal pi : parsed) { animalUpdater.updateItem(pi); } // commit transaction // catch: rollback transaction, rethrow // finally: close database connection } </code></pre> <p>The parser returns either a ParsedCat, or ParsedDog, or whatever, all of which inherit from a common ParsedAnimal class:</p> <pre><code>public abstract class ParsedAnimal {...} public class ParsedCat extends ParsedAnimal {...} public class ParsedDog extends ParsedAnimal {...} </code></pre> <p>Then I have an Updater which needs to take the parsed item and inject the contents into the database:</p> <pre><code>public abstract class Updater { public abstract void updateItem(ParsedAnimal parsed); } public class CatUpdater extends Updater { @Override public void updateItem(ParsedCat parsed) {} } public class DogUpdater extends Updater {...} </code></pre> <p>This doesn't work &mdash; the contract for Updater specifies that updateItem() accepts a ParsedAnimal, and CatUpdater and DogUpdater both break that contract by only accepting a specific type of animal.</p> <p>What I have is a parallel class hierarchy &mdash; ParsedX matches up one to one with XUpdater. The <a href="http://www.codinghorror.com/blog/2006/05/code-smells.html" rel="nofollow" title="Code Smells">Code Smells</a> page on Coding Horror suggests merging the two class hierarchies into a single hierarchy, but I feel like the "thing being worked on" and the "thing doing the working" are different enough that they should be separate classes.</p> <p>Is there a neat way of structuring this, or some design pattern that would come in handy?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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