I know that delegating from one method to another in the same class is okay as it reduces code duplication, but is delegating calls to other class types considered bad practice?
For example:
Doing this is okay.
double Point::GetDistanceFrom(const Point& point) const {
return GetDistanceFrom(this->GetX(), this->GetY(), point.GetX(), point.GetY());
}
double Point::GetDistanceFrom(const Point& one, const Point& two) {
return GetDistanceFrom(one.GetX(), one.GetY(), two.GetX(), two.GetY());
}
double Point::GetDistanceFrom(double x1, double y1, double x2, double y2) {
return std::sqrt(GetDistanceFromSquared(x1, y1, x2, y2));
}
double Point::GetDistanceFromSquared(double x1, double y1, double x2, double y2) {
x2 -= x1;
y2 -= y1;
return (x2 * x2 + y2 * y2);
}
double Point::GetDistanceFromSquared(const Point& one, const Point& two) {
return GetDistanceFromSquared(one.GetX(), one.GetY(), two.GetX(), two.GetY());
}
But what about this?
double Point::GetDistanceFrom(const Line& line, bool isInfinite) const {
if(isInfinite) return line.ptLineDist(line.GetPointOne().GetX(), line.GetPointOne().GetY(), line.GetPointTwo().GetX(), line.GetPointTwo().GetY(), this->GetX(), this->GetY());
return line.ptSegDist(line.GetPointOne().GetX(), line.GetPointOne().GetY(), line.GetPointTwo().GetX(), line.GetPointTwo().GetY(), this->GetX(), this->GetY());
}
And this?
double Line::GetDistanceFrom(const Point& point, bool isInfinite) const {
return point.GetDistanceFrom(*this, isInfinite);
}
The OO design rule that is probably most applicable is encapsulation. The
Pointclass shouldn’t really know that theptSegDistmethod exists onLine. But it is free to do anything it wants with its public interface.In this case, it seems like you could easily swap the responsibilities you are delegating:
Calling existing getters on a class does not violate any OO or encapsulation rule. In this case, it requires slightly less code, too.