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条回答
一纸荒年 Trace。
2楼-- · 2019-02-08 16:55

I prefer the first one. The condition should be as simple as possible and it should be fairly obvious which is simpler out of condition and !condition

查看更多
老娘就宠你
3楼-- · 2019-02-08 16:56
  1. put the common path first
  2. turn negative cheking into positive ones (!full == empty)
查看更多
干净又极端
4楼-- · 2019-02-08 16:56

I'm horrible when it comes to how I set up if statements. Basically, I set it up based on what exactly I'm looking for, which leads everything to be different.

if (userinput = null){
explodeViolently();
} else {
actually do stuff;
}

or perhaps something like

if (1+1=2) {
do stuff;
} else {
explodeViolently();
}

Which section of the if/else statement actually does things for me is a bad habit of mine.

查看更多
家丑人穷心不美
5楼-- · 2019-02-08 17:00

Two (contradictory) textbook quotes:

Put the shortest clause of an if/else on top

--Allen Holub, "Enough Rope to Shoot Yourself in the Foot", p52

Put the normal case after the if rather than after the else

--Steve McConnell, "Code Complete, 2nd ed.", p356

查看更多
Explosion°爆炸
6楼-- · 2019-02-08 17:00

Intel Pentium branch prediction pre-fetches instructions for the "if" case. If it instead follows the "else" branch: it has the flush the instruction pipeline, causing a stall.

If you care a lot about performance: put the most likely outcome in the 'if' clause.

Personally i write it as

if (expected)
{
   //expected path
}
else
{
   //fallback other odd case
} 
查看更多
登录 后发表回答