Should a function pass in one of two classes or be free?

I am relatively new to OOP. Sometimes I come across situations when I'm not sure where the method should go. I will try to give a minimal example; I hope I don’t go overboard and make it too abstract.

Say I have a Point class that contains the position of a point and a Line class that contains the equation of a line. Now I need a method that calculates the (perpendicular) distance between a Point and a Line . I could do:

  • Point :: distance_to_line (line L)
  • Line :: distance_to_point (point P)
  • autonomous function: point_line_distance (line L, point P)

Is there a preferred way in OOP in general or is it language dependent? In C ++, a stand-alone function is an option, but from my limited understanding of Java, this does not allow for independent functions. In this case, would you create a class of type PointLineDistanceCalculator ?

+6
source share
3 answers

Your third option elsewhere, which is not part of the Point or Line class, is the best option.

Points should not know about Lines and vice versa. Otherwise, they will be tightly connected.

http://en.wikipedia.org/wiki/Loose_coupling

However, there may be another class that knows about everyone.

In java, I would probably make a third class, Distance or DistanceCalculator , that could calculate the distances between multiple objects.

 Distance.between(Point a, Point b) Distance.between(Point a, line l) 

etc.

+4
source

In java, you can always create a free-standing function as a static method of one of two classes (or the third helper class).

I don’t think that there is a preferred way at all, but you could use all three for more flexibility and reuse the code.

For example, one method will contain logic:

 class Point { ... float distToLine (Line l) { .... return some result; } ... } 

and then other methods will call the original method:

 class Line { ... float distToPoint (Point p) { return p.distToLine (this); } ... static float pointToLineDistance (Point p, Line l) { return p.distToLine (l); } ... } 
+1
source

The fourth option is to find / build a common ancestor in the class hierarchy, which could be something like "GeometricEntity". Everything for which "distance to infinity GeometricEntity" matters.

0
source

Source: https://habr.com/ru/post/972610/


All Articles