我知道在同一个类中将一个方法委托(delegate)给另一个方法是可以的,因为它减少了代码重复,但是将调用委托(delegate)给其他类类型是否被认为是不好的做法?
例如:
这样做没问题。
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());
}
但是这个呢?
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());
}
还有这个?
double Line::GetDistanceFrom(const Point& point, bool isInfinite) const {
return point.GetDistanceFrom(*this, isInfinite);
}
最佳答案
is delegating calls to other class types considered bad practice?
可能最适用的 OO 设计规则是 encapsulation . Point
类不应该真正知道ptSegDist
方法存在于Line
上。但它可以通过其公共(public)界面自由地做任何它想做的事情。
在这种情况下,您似乎可以轻松地交换您委派的职责:
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());
}
在类上调用现有的 getter 不会违反任何 OO 或封装规则。在这种情况下,它也需要稍微少一点的代码。
关于c++ - 在类(class)之间委派电话是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6643615/