5

I have a Circle class and a LineSegment class, and I want to implement a method that returns two points (or one, or none) for the intersections.

How do I know which class to put this method in? Would a separate "middle-man" Intersections class be better?

  • Are you going to support intersection of Circle with Circle as well, or add other shapes, because that would make things interesting, or are you just solving this very specific problem of intersection of Circle and LineSegment. – Erik Eidt Feb 24 '18 at 15:51
  • @ErikEidt I'm working on a geometry library for fun, so there would be other shapes, including, for example, Circle-Circle intersection as well as LineSegment-LineSegment intersections – MCMastery Feb 24 '18 at 15:54
  • Can you describe your class hierarchy more? Do Circle and LineSegment inherit from the same base class? Are there other geometric classes involved that will need intersection checks? – user1118321 Feb 24 '18 at 15:58
8

What about of implementing a free function taking the subjects as parameters, instead of binding it to a specific class, if you can't tell which it should belong to specifically?

Would a separate "middle-man" Intersections class be better?

If you're working with a programming language like c# or java, which doesn't support free functions, you probably should have such Intersections (static) class, e.g. like in c#:

public static class Intersections {
    public static IList<Point> GetIntersectionPoints(Circle c, LineSegment ls) {
        // ...
    }
}
4

Then you might consider a base class Shape or interface IShape where the Intersection method is declared. You can override it so that each shape can implement its own version.

However, eventually, you'll probably need double-dispatch if you're using a language that doesn't have multiple dispatch or multi-methods.

While double-dispatch sometimes is a code smell, I think that when you have a function like intersection between two shapes, which needs to understand both shapes in order to work well, it seems appropriate.

1

The independent Intersections class seems a good idea. To make it work with different type (lines, circles, ellipses, squares, hexagons) you can use overloading of the common "GetIntersectionPoints" function. Repeated code sections can be reduced by defining support functions unique to the Intersections class used only in the Intersections class.

0

I think, intersection is not something a circle nor the line should know about. There should be something higher, like a ´Plane´ or more abstract ´ShapesOnAPlaneRelation´ with a method you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.