samedi 28 février 2015

Best pattern for strong typing of class relations

I'm looking for a way to allow relation between instances at compile time. In an abstract way, that means that several subtypes of an interface are related to multiple properties of the same type, but not all of them compatible in a logical way. I'd like to check it at compile time.


The scenario is such as:



  • An Anmimal instance receives a country instance in the constructor (country where it lives).


Solutions:



  • Runtime checking trhough XML for instance and validation




<Animal>
<Type>Lion</Type>
<Countries>
<Country>Zimbabwe</Country>
<Country>Kenya</Country>
</Countries>
</Animal>

<Animal>
<Type>Gorilla</Type>
<Countries>
<Country>Zimbabwe</Country>
<Country>Botswana</Country>
</Countries>
</Animal>


But this could only fail at runtime



  • Create a GorillaCountry, BotswanCountry and KenyaCountry Country subinterface for each combination of properties, but this is a bit unmantainable if there is 200 mappings.


What I look for is some kind of pattern that approaches in a nice and scalable way this type checking at compile time:



if (animal instanceOf Lion){
if (country instanceOf Botswana) throw new UnsupportedMApping("There are no lions in botswana")
}Kenya
else if (animal instanceOf Gorilla){
if (country instanceOf Kenya) throw new UnsupportedMapping("There are no gorillas in kenya")
}


Perhaps a tricky way with generics or maps...


Aucun commentaire:

Enregistrer un commentaire