前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.133:避免保护型数据成员‍

C++核心准则C.133:避免保护型数据成员‍

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

C.133: Avoid protected data

C.133:避免保护型数据成员‍

Reason(原因)

protected data is a source of complexity and errors.protected data complicates the statement of invariants.protected data inherently violates the guidance against putting data in base classes, which usually leads to having to deal with virtual inheritance as well.

保护型数据成员是复杂性和错误的源头。保护型数据使不变式的表现更加复杂。保护数据成员天生违反不要将数据放进基类的原则,这通常也会导致必须同时处理虚继承。

Example, bad(反例)

代码语言:javascript
复制
class Shape {
public:
    // ... interface functions ...
protected:
    // data for use in derived classes:
    Color fill_color;
    Color edge_color;
    Style st;
};

Now it is up to every derived Shape to manipulate the protected data correctly. This has been popular, but also a major source of maintenance problems. In a large class hierarchy, the consistent use of protected data is hard to maintain because there can be a lot of code, spread over a lot of classes. The set of classes that can touch that data is open: anyone can derive a new class and start manipulating the protected data. Often, it is not possible to examine the complete set of classes, so any change to the representation of the class becomes infeasible. There is no enforced invariant for the protected data; it is much like a set of global variables. The protected data has de facto become global to a large body of code.

现在每个派生的Shape类都需要正确地处理保护数据。这种做法曾经很流行,但也是维护问题的主要来源。在大规模类层次中,由于代码量很大而且分散在很多类中,因此使用保护数据的一贯性很难维持。可以操作数据的类的集合是开放的:任何人都可以派生出一个新类并操作保护型数据。通常无法完全检查所有这些类,因此对基类表现(数据成员,译者注)的任何修改都变得不可能。不存在针对保护成员的强制性不变量;它们更像一套全局变量。对于大量代码来说,保护类型数据成员事实上已经成为全局的了。

Note(注意)

Protected data often looks tempting to enable arbitrary improvements through derivation. Often, what you get is unprincipled changes and errors.Prefer private data with a well-specified and enforced invariant. Alternative, and often better, keep data out of any class used as an interface.

保护型数据成员经常看起来试图允许通过派生实现自由的改进。通常,你得到的是无规则的修改和错误。更好的选择是包含良好定义的强制不变量的私有数据成员。不将数据放进任何作为接口使用的类中通常也是比较好的选择。

Note(注意)

Protected member function can be just fine.

保护型成员函数问题不大。

Enforcement(实施建议)

Flag classes with protected data.

提示含有保护型数据成员的类。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c133-avoid-protected-data


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

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

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

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

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

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

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

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