What to put in the IF block and what to put in the

2019-02-08 16:22发布

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

So if you've got:

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

How do you decide if it's better like that, or like this:

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

My heuristics are:

  1. Keep the condition positive (less mental calculation when reading it)
  2. Put the most common path into the first block

23条回答
家丑人穷心不美
2楼-- · 2019-02-08 16:39

For me it depends on the condition, for example:

if (!PreserveData.Checked)
{  resetfields();}

I tend to talk to my self with what I want the logic to be and code it to the little voice in my head.

查看更多
【Aperson】
3楼-- · 2019-02-08 16:40

If the code is to check for an error condition, I prefer to put that code first, and the "successful" code second; conceptually, this keeps a function call and its error-checking code together, which makes sense to me because they are related. For example:

  if (!some_function_that_could_fail())
  {
     // Error handling code
  }
  else
  {
     // Success code
  }
查看更多
时光不老,我们不散
4楼-- · 2019-02-08 16:41

It depends on your flow. For many functions, I'll use preconditions:

bool MyFunc(variable) {
    if (variable != something_i_want)
        return false;

    // a large block of code
    // ...
    return true;
}

If I need to do something each case, I'll use an if (positive_clause) {} else {} format.

查看更多
Deceive 欺骗
5楼-- · 2019-02-08 16:47

When I am looking at data validation, I try to make my conditions "white listing" - that is, I test for what I will accept:

if DataIsGood() then
   DoMyNormalStuff
else
   TakeEvasiveAction

Rather than the other way around, which tends to degenerate into:

if SomeErrorTest then
  TakeSomeEvasiveAction
else if SomeOtherErrorCondition then
  CorrectMoreStupidUserProblems
else if YetAnotherErrorThatNoOneThoughtOf then
  DoMoreErrorHandling
else
  DoMyNormalStuff
查看更多
放荡不羁爱自由
6楼-- · 2019-02-08 16:47

If one of the two paths is very short (1 to 10 lines or so) and the other is much longer, I follow the Holub rule mentioned here and put the shorter piece of code in the if. That makes it easier to see the if/else flow on one screen when reviewing the code.

If that is not possible, then I structure to make the condition as simple as possible.

查看更多
三岁会撩人
7楼-- · 2019-02-08 16:50

I agree with Oli on using a positive if clause when possible.

Just please never do this:

if (somePositiveCondition)
else {
    //stuff
}

I used to see this a lot at one place I worked and used to wonder if one of the coders didn't understand how not works...

查看更多
登录 后发表回答