c++ - 在类(class)之间委派电话是不好的做法吗?

标签 c++

我知道在同一个类中将一个方法委托(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/

相关文章:

c++将数组大小扩大两倍的方法?

c++ - 如何使用 sys/mount 挂载 NFS 系统?

c++ - 如何创建一个可以在 GUI 对话框模式下或通过命令行启动的 C++ MFC 程序?

c++ - 可变参数模板函数是否以相反的顺序调用 lambda 参数?

c++ - 如何在C++ Visual Studio中获得此输出?

c++ - 从 P 帧和 B 帧创建 I 帧

C++ 概念 : CRTP

c++ - 如何线性化两个浮点变量的乘积

c++ - 为什么bernoulli_distribution::param_type 的构造函数是显式的?

c++ - 将一组字符串与一个字符串进行比较的最快方法是什么?