I am writing a particle transport code. In this code physical objects implement an interface Volume. One implementer of Volume is the case of interest for this code– the Particle class. In my design, Volumes contain other Volumes all the way down to the smallest Volume implementer, Particle. This will work great as long as Particles want to fly around unmonitored through volumes having interactions.
However, the moment I want to implement some sort of Particle detector Volume, which will record information about the Particle, I have a problem. The Volume interface doesn’t contain a way to get the special type of information a Particle has. If a Particle makes its way into the detector Volume, I will have to do something like check its type with reflection before I cast it to Particle from Volume and call the Particle methods. Generally (from what I have seen) this type of thing gets flagged with a “bad design” label.
I could make it so that only Particles can cross Volume boundaries in the Volume interface (tie the interface to the special case Particle), but I don’t really want to impose that limit on my code. It’s possible that I may want to allow volumes to move around and join later.
So does this sound like a bad design? Is there another obvious way to handle this problem? I will attach code if need be, but the general problem seems independent of my particulars (and fairly independent of language).
Thanks in advance. I really appreciate all the knowledge here on SO.
From what I’ve read, dynamic casting is not considered terrible in Java. Simple type checking is much less extreme than using the full Reflection API.
You can either attempt the dynamic cast and catch a possible
ClassCastException, or do anisinstance Particlecheck before casting.Conceptually, it may make more sense for Particles to implement an interface that indicates they have the information your Particle detector wants to record. Without knowing more about your design we can’t say.