Should I use an interface when methods are only similar?

Posted by Joshua Harris on Programmers See other posts from Programmers or by Joshua Harris
Published on 2012-11-11T06:14:19Z Indexed on 2012/11/11 11:27 UTC
Read the original article Hit count: 395

I was posed with the idea of creating an object that checks if a point will collide with a line:

public class PointAndLineSegmentCollisionDetector {
    public void Collides(Point p, LineSegment s) {
        // ...
    }
}

This made me think that if I decided to create a Box object, then I would need a PointAndBoxCollisionDetector and a LineSegmentAndBoxCollisionDetector. I might even realize that I should have a BoxAndBoxCollisionDetector and a LineSegmentAndLineSegmentCollisionDetector. And, when I add new objects that can collide I would need to add even more of these.

But, they all have a Collides method, so everything I learned about abstraction is telling me, "Make an interface."

public interface CollisionDetector {
    public void Collides(Spatial s1, Spatial s2);
}

But now I have a function that only detects some abstract class or interface that is used by Point, LineSegment, Box, etc.. So if I did this then each implementation would have to to a type check to make sure that the types are the appropriate type because the collision algorithm is different for each different type match up.

Another solution could be this:

public class CollisionDetector {
    public void Collides(Point p, LineSegment s) { ... }
    public void Collides(LineSegment s, Box b) { ... }
    public void Collides(Point p, Box b) { ... }
    // ...
}

But, this could end up being a huge class that seems unwieldy, although it would have simplicity in that it is only a bunch of Collide methods.

This is similar to C#'s Convert class. Which is nice because it is large, but it is simple to understand how it works. This seems to be the better solution, but I thought I should open it for discussion as a wiki to get other opinions.

© Programmers or respective owner

Related posts about object-oriented-design

Related posts about interfaces