C++核心准则ES.79:使用default处理一般case

面向对象思考

共 2185字,需浏览 5分钟

 ·

2020-06-06 23:21

abc45b77a6a4fa123f8d83a3479acca2.webp

ES.79: Use default to handle common cases (only)

ES.79:使用default处理一般case


Reason(原因)

Code clarity. Improved opportunities for error detection.

代码清晰性。增加发现错误的机会。


Example(示例)

enum E { a, b, c , d };

void f1(E x)
{
switch (x) {
case a:
do_something();
break;
case b:
do_something_else();
break;
default:
take_the_default_action();
break;
}
}

Here it is clear that there is a default action and that cases a and b are special.

可以清晰地看出存在一个默认case,而a和b是特殊case。


Example(示例)

But what if there is no default action and you mean to handle only specific cases? In that case, have an empty default or else it is impossible to know if you meant to handle all cases:

如果就是没有默认动作,你只想处理特殊case时应该怎么做呢?这种情况下,保留一个空的默认处理,否则不可能知道你是否意图处理所有case。

void f2(E x)
{
switch (x) {
case a:
do_something();
break;
case b:
do_something_else();
break;
default:
// do nothing for the rest of the cases
break;
}
}

If you leave out the default, a maintainer and/or a compiler may reasonably assume that you intended to handle all cases:

如果漏掉了default,维护者或者编译器可能会合情合理的假设你意图处理所有case。

void f2(E x)
{
switch (x) {
case a:
do_something();
break;
case b:
case c:
do_something_else();
break;
}
}

Did you forget case d or deliberately leave it out? Forgetting a case typically happens when a case is added to an enumeration and the person doing so fails to add it to every switch over the enumerators.

你是忘记了case d还是故意遗漏的?忘记一个case通常发生在增加枚举值之后却没有为所有switch语句增加针对该值的处理的时候。


Enforcement(实施建议)

Flag switch-statements over an enumeration that don't handle all enumerators and do not have a default. This may yield too many false positives in some code bases; if so, flag only switches that handle most but not all cases (that was the strategy of the very first C++ compiler).

标记针对枚举类型的、没有处理所有枚举值并且不包含default处理的switch语句。对于某些代码这种做法可能会产生太多的假阳性;如果发生这种情况,只标记处理了大部分case但不是全部case的情况(这正是很早期的C++编译器采用的策略)。


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es79-use-default-to-handle-common-cases-only




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

关注微信公众号【面向对象思考】轻松学习每一天!

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


浏览 22
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

举报