0

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 Animal 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, BotswanaCountry 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") 
}
//for 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...

erhun
  • 3,549
  • 2
  • 35
  • 44
Whimusical
  • 6,401
  • 11
  • 62
  • 105

1 Answers1

1

What you want is something like the java 8 pluggable type system.

Examples and a framework for working with it are here.

It seems entirely possible, though not necessarily sensible, to use that to create @Animal and @Country annotations. Then set up a corresponding type checker that queried an appropriate database to see if they were extinct yet.

soru
  • 5,464
  • 26
  • 30
  • Mmhhh that-s a very interesting approach. I'll research if I can make either a "@Countries (Zimbabwe,Kenya,)" in Lion class or either a "@Animals (Lion, Gorilla)" in Zimbabwe class. – Whimusical Feb 28 '15 at 13:03