Should if/else statements be arranged by rareness of cases or difficulty of dealing with them?

In some code I’m writing right now, I have something like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if (uncommon_condition) {
do_something_simple();
} else {
do();
something();
long();
and();
complicated();
}
</code>
<code>if (uncommon_condition) { do_something_simple(); } else { do(); something(); long(); and(); complicated(); } </code>
if (uncommon_condition) {
    do_something_simple();
} else {
    do();
    something();
    long();
    and();
    complicated();
}

Part of me thinks “It’s fine the way it’s written. Simple cases should go first and more complicated cases should go next.” But another part says: “No! The else code should go under the if, because if is for dealing with unusual cases and else is for dealing with all other cases.” Which is correct or preferable?

2

Order by their likelihood of being executed. The most common, most likely, etc. condition(s) should go first.

The “difficulty of dealing with them” should be dealt with by code structure, abstraction, etc. in the example the else block could be refactored to single method call. You want your if clauses to be at the same abstract level.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if ( ! LotteryWinner ) {
GoToWorkMonday();
} else {
PlanYearLongVacation();
}
</code>
<code>if ( ! LotteryWinner ) { GoToWorkMonday(); } else { PlanYearLongVacation(); } </code>
if ( ! LotteryWinner ) {
    GoToWorkMonday();
} else {
    PlanYearLongVacation();
}

5

Try to enhance readability. One way is to place the longer code block into the else part.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if (s == null)
// short code
else
// long
// code
// block
</code>
<code>if (s == null) // short code else // long // code // block </code>
if (s == null)
     // short code
else 
     // long 
     // code
     // block

is more readable than

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if (s != null)
// long
// code
// block
else
// short code
</code>
<code>if (s != null) // long // code // block else // short code </code>
if (s != null)
    // long
    // code
    // block
else
    // short code

2

No fixed rule as such I heard about the usage but I follow like this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if(usual)
{
(more often)
}
else (unusual)
{
(rarely occurring)
}
</code>
<code>if(usual) { (more often) } else (unusual) { (rarely occurring) } </code>
if(usual)
{
(more often)
}
else (unusual)
{
(rarely occurring)
}

But if both have same function with different properties then better go for unusual first then usual so that you can save one instruction.


Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if(x == 0) // 1
{x = 1;} // 2
else
{x = 2;} // 3
</code>
<code>if(x == 0) // 1 {x = 1;} // 2 else {x = 2;} // 3 </code>
if(x == 0)  // 1
  {x = 1;}  // 2
else
  {x = 2;}  // 3

For above code assembly code will be something like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>1. 000d 837DFC00 cmpl $0, -4(%ebp)
0011 7509 jne .L2
2. 0013 C745FC01 movl $1, -4(%ebp)
001a EB07 jmp .L3
.L2:
3.001c C745FC02 movl $2, -4(%ebp)
.L3:
</code>
<code>1. 000d 837DFC00 cmpl $0, -4(%ebp) 0011 7509 jne .L2 2. 0013 C745FC01 movl $1, -4(%ebp) 001a EB07 jmp .L3 .L2: 3.001c C745FC02 movl $2, -4(%ebp) .L3: </code>
1. 000d 837DFC00        cmpl    $0, -4(%ebp)
   0011 7509            jne .L2

2. 0013 C745FC01        movl    $1, -4(%ebp)
   001a EB07            jmp .L3

    .L2:
3.001c C745FC02         movl    $2, -4(%ebp)

        .L3:

If condition inside if is true then flow is 1->2( 4 intructions)
IF condition inside if is false then flow is 1->3 (3 intructions)

So its better to put unusual or rarely occurring events in if part and normal condition in else so that we can save one instruction every time 😉

I have found that the exact opposite pattern leads to easier to read code, and reduces or eliminates nested if statements. I refer to this as a “gauntlet” pattern. (In story telling, a gauntlet would be a series of challenges that have to be met successfully before the final task is completed.) By handling your edge cases first, you allow the main body of your code to be clean and concise:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if(gauntlet_1){ handle the first gauntlet condition };
if(gauntlet_2){ handle the second gauntlet condition };
...
// All preconditions (gauntlets) have been successfully handled
// Perform your main task here
</code>
<code>if(gauntlet_1){ handle the first gauntlet condition }; if(gauntlet_2){ handle the second gauntlet condition }; ... // All preconditions (gauntlets) have been successfully handled // Perform your main task here </code>
if(gauntlet_1){ handle the first gauntlet condition }; 
if(gauntlet_2){ handle the second gauntlet condition };
...
// All preconditions (gauntlets) have been successfully handled

// Perform your main task here

3

For me it’s more about the conditions than the complexity of the code they execute. You need to order the conditions so as to trap unusual conditions first, then the more common after. Also, if the else code is really long and complicated, I’d probably make a sub for that, to keep the conditional part obvious for the reader.

I don’t have a fixed rule, but generally I follow this – first, consider where there’s a missed design pattern that will factor this out. If not, I write it so that the condition in the if is the most clearly understood. That is, avoiding double negatives and the like.

As for such scenarios there is no thumb rule for it. But possibly we can follow to write the positive or most likely code in the if block and left out in the else block or default cases.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật