C++核心准则C.131: 避免无意义的getters和setters‍

共 1847字,需浏览 4分钟

 ·

2020-02-05 23:23

e16ae9c5386804e64071d593bef64147.webp



C.131: Avoid trivial getters and setters

C.131: 避免无意义的getters和setters‍




Reason(原因)




A trivial getter or setter adds no semantic value; the data item could just as well be public.

无意义的getter和setter不会增加任何语义上的价值,数据项只要定义为public就好。


Example(示例)




class Point {   // Bad: verbose
    int x;
    int y;
public:
    Point(int xx, int yy) : x{xx}, y{yy} { }
    int get_x() const { return x; }
    void set_x(int xx) { x = xx; }
    int get_y() const { return y; }
    void set_y(int yy) { y = yy; }
    // no behavioral member functions
};

Consider making such a class a struct -- that is, a behaviorless bunch of variables, all public data and no member functions.

考虑将这样的类定义为struct--也就是说,不包含行为的数据群,所有数据都公开,没有成员函数。

struct Point {
    int x {0};
    int y {0};
};

Note that we can put default initializers on member variables: C.49: Prefer initialization to assignment in constructors.

注意我们可以为成员变量设置初始化器:C.49:初始化比在构造函数中复制更好。


Note(注意)




The key to this rule is whether the semantics of the getter/setter are trivial. While it is not a complete definition of "trivial", consider whether there would be any difference beyond syntax if the getter/setter was a public data member instead. Examples of non-trivial semantics would be: maintaining a class invariant or converting between an internal type and an interface type.

这条准则的关键是getter/setter的语义是不是有意义。如果不能完全定义“无意义”,考虑如果getter/setter是公有成员的话是否存在任何的不同。有意义的语义的示例:维持类的不变量或者在内部数据类型和接口数据类型之间进行的转换。


Enforcement(实施建议)




Flag multiple get and set member functions that simply access a member without additional semantics.

如果存在多个get和set成员函数,只是简单地访问数据成员却不包含附加意义,进行提示。


原文链接:




https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c130-for-making-deep-copies-of-polymorphic-classes-prefer-a-virtual-clone-function-instead-of-copy-constructionassignment




觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

浏览 38
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报