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

a1dbb29136dfdcb6b6905468190674d3.png

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

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

4b0997c5a85afa6ac0eb2fa6d77a9165.png

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


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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值