Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is delegating calls between classes bad practice?

Tags:

c++

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);
}
 
like image 462
Casey Avatar asked Mar 06 '26 15:03

Casey


1 Answers

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.

like image 99
Merlyn Morgan-Graham Avatar answered Mar 09 '26 05:03

Merlyn Morgan-Graham