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);
}
is delegating calls to other class types considered bad practice?
The OO design rule that is probably most applicable is encapsulation. The Point class shouldn't really know that the ptSegDist method exists on Line. 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:
double Point::GetDistanceFrom(const Line& line, bool isInfinite) const {
return line.GetDistanceFrom(*this, isInfinite);
}
double Line::GetDistanceFrom(const Point& point, bool isInfinite) const {
if(isInfinite) return ptLineDist(GetPointOne().GetX(), GetPointOne().GetY(), GetPointTwo().GetX(), GetPointTwo().GetY(), point.GetX(), point.GetY());
return ptSegDist(GetPointOne().GetX(), GetPointOne().GetY(), GetPointTwo().GetX(), GetPointTwo().GetY(), point.GetX(), point.GetY());
}
Calling existing getters on a class does not violate any OO or encapsulation rule. In this case, it requires slightly less code, too.
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