I m having an issue in OO design where I end up with duplicate code in 2 different classes. Here s what s going on:
In this example, I want to detect collision between game objects.
I have a base CollisionObject that holds common methods (such as checkForCollisionWith) and CollisionObjectBox, CollisionObjectCircle, CollisionObjectPolygon that extend the base class.
This part of design seems ok, but here s what s troubling me: calling
aCircle checkForCollisionWith: aBox
will perform a circle vs box collision check inside Circle subclass. In reverse,
aBox checkForCollisionWith: aCircle
will perform box vs circle collision check inside Box subclass.
Issue here is that Circle vs Box collision code is duplicate, since it s in both Box and Circle classes. Is there a way to avoid this, or am I approaching this problem the wrong way? For now, I m leaning towards having a helper class with all the duplicate code and call it from the aCircle and aBox objects to avoid duplicates. I m curious if there s more elegant OO solution to this, though.