Java实现会员和非会员,如何选择会员和非会员功能?

Effective C++对"Prefer non-member non-frend functions to member functions"说(第23项) . 理由对我来说很有意义:它最小化了API "surface area" . 但在实践中,我经常发现很难说服人们(包括我自己)遵循 . 例如,假设我有一些形状类,它们应该支持周长和面积计算:

// @interface

class Shape {

public:

virtual double Area() = 0;

virtual double Perimeter() = 0;

}

class Rectangle : public Shape {

public:

Rectangle(double width, double height);

double width();

double height();

...

};

class Circle : public Shape {

public:

Circle(double radius);

double radius();

...

};

根据这个建议,似乎Area和Perimeter应该是非成员非朋友函数(不是方法),因为它们可以 . 例如 . 可以从width和height方法计算Rectangle的区域,如下所示:

double Area(const Rectangle& rectangle) {

return rectangle.width() * rectangle.height();

}

实际上,Rectangle和Circle都没有任何内部状态,它们的吸气剂都没有暴露,而且很难想象会是怎样的 . 因此,对这些操作的任何函数都不应该是一种方法 . 另一个例子:

// The diameter of a shape is the (circle) diameter of the smallest circle

// that contains a shape.

double Diameter(const Rectangle& rectangle) {

double w = rectangle.width();

double h = rectangle.height();

return sqrt(w * w + h * h);

}

我在这里错过了什么吗?或者这实际上是不好的建议?

Effective C++对"Prefer non-member non-frend functions to member functions"说(第23项) . 理由对我来说很有意义:它最小化了API "surface area" . 但在实践中,我经常发现很难说服人们(包括我自己)遵循 . 例如,假设我有一些形状类,它们应该支持周长和面积计算: // @interface class Shape { public: virtual double Area() = 0; virtual double Perimeter() = 0; } class Rectangle : public Shape { public: Rectangle(double width, double height); double width(); double height(); ... }; class Circle : public Shape { public: Circle(double radius); double radius(); ... }; 根据这个建议,似乎Area和Perimeter应该是非成员非朋友函数(不是方法),因为它们可以 . 例如 . 可以从width和height方法计算Rectangle的区域,如下所示: double Area(const Rectangle& rectangle) { return rectangle.width() * rectangle.height(); } 实际上,Rectangle和Circle都没有任何内部状态,它们的吸气剂都没有暴露,而且很难想象会是怎样的 . 因此,对这些操作的任何函数都不应该是一种方法 . 另一个例子: // The diameter of a shape is the (circle) diameter of the smallest circle // that contains a shape. double Diameter(const Rectangle& rectangle) { double w = rectangle.width(); double h = rectangle.height(); return sqrt(w * w + h * h); } 我在这里错过了什么吗?或者这实际上是不好的建议?
经验分享 程序员 微信小程序 职场和发展