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:
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
?
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
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);
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With