前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.131: 避免无意义的getters和setters‍

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

作者头像
面向对象思考
发布2020-03-25 16:39:51
5230
发布2020-03-25 16:39:51
举报

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(示例)

代码语言:javascript
复制
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--也就是说,不包含行为的数据群,所有数据都公开,没有成员函数。

代码语言:javascript
复制
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


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

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档