Stage1st

 找回密码
 立即注册
搜索
打印 上一主题 下一主题

[其他] [码农]一个成员变量既有get又有set,那为什么不设为public呢?

[复制链接]
楼主
发表于 2023-11-13 15:53 | 显示全部楼层
C.131: Avoid trivial getters and setters
Reason

A trivial getter or setter adds no semantic value; the data item could just as well be 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 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.
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.

Enforcement

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

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|Archiver|上海互联网违法和不良信息举报中心|网上有害信息举报专区|962110 反电信诈骗|举报电话 021-62035905|stage1st 沪ICP备13020230号-1 沪公网安备 31010702007642号

GMT+8, 2024-5-15 05:01 , Processed in 0.015838 second(s), 6 queries , Gzip On, Redis On.

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表