Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a function go in one/both of two classes or be free-standing?

Tags:

java

c++

oop

I am relatively new to OOP. Sometimes I come across situations where I'm not sure where a 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 which holds the position of a point, and a Line class which holds the equation of a line. I now need a method that computes the (perpendicular) distance between a Point and a Line. I could do:

  • Point::distance_to_line(Line L)
  • Line::distance_to_point(Point P)
  • a free-standing function: point_line_distance(Line L, point P)

Is there a preferred way in OOP in general, or is it language-dependant? In C++ a free-standing function is an option, but from my limited understanding of Java, it does not allow free-standing functions. In that case would you create a class like PointLineDistanceCalculator?

like image 681
MGA Avatar asked Jul 21 '14 19:07

MGA


2 Answers

Your 3rd option of some other place that is not in the Point or Line class is the best option.

Points shouldn't have to know about Lines and vice versa. Otherwise, they will be tightly coupled.

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

However, there can be some other class that knows about both.

In java, I would probably made a 3rd Distance class or DistanceCalculator that could compute distances between several objects.

Distance.between(Point a, Point b)

Distance.between(Point a, line l)

etc

like image 188
dkatzel Avatar answered Oct 04 '22 22:10

dkatzel


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

I don't think there's a preferred way in general, but you could have all three for the most flexibility, and reuse the code.

For example, one method would hold the logic :

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

and then the 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);
   }
...
}
like image 24
Eran Avatar answered Oct 04 '22 22:10

Eran