什么放在IF块和什么放在ELSE块? [英] What to put in the IF block and what to put in the ELSE block?

查看:178
本文介绍了什么放在IF块和什么放在ELSE块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个小样式问题,但您添加到代码中的每一点都是可读性。

This is a minor style question, but every bit of readability you add to your code counts.

所以如果你有:

if (condition) then
{
   // do stuff
}
else
{
   // do other stuff
}

或者像这样:

   if (!condition) then
   {
     // do other stuff
   {
   else
   {
     // do stuff
   }

我的启发式是:


  1. 保持条件为正)

  2. 将最常见的路径放入
    第一个块中


推荐答案

我喜欢把最常见的路径放在第一位,我坚信嵌套缩减,所以我会打破,继续,或返回,而不是elsing的可能。我通常喜欢对阳性条件进行测试,或者反转[和命名]阴性条件为阳性。

I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive.

if (condition)
    return;

DoSomething();

我发现通过大幅减少else的使用我的代码更可读和可维护,当我必须使用else它几乎总是一个非常好的候选人一个更结构化的switch语句。

I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.

这篇关于什么放在IF块和什么放在ELSE块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆