Effective "if-else" ~How Experts Think About Branching~
This article was automatically translated from Japanese by AI. Read the original Japanese version →
Table of Contents
If you're an experienced programmer, I'm sure you already know what an if statement is.
In this article, I'll look at how if features and syntax differ across languages, and derive safer ways to write them. The key takeaway is that patterns that cause compile errors in static languages are better avoided—or used only in well-chosen places—in dynamic languages too.
Depending on the language, it may be a statement, an expression, or a function, though I'll mostly refer to it as a statement in this article.
Feature Differences
Different languages have all sorts of syntax for if statements, but here I'll focus mainly on differences in their features.
The Basics (Branching)
The most basic way to write it looks something like this—a Ruby-like style.
if 条件 条件がtrueだったら何かする end
if 条件 trueの場合に実行する文 else falseの場合に実行する文 end
Initialization
This is a feature implemented in Go. http://golang.jp/effective_go#if
if err := file.Chmod(0664); err != nil { log.Print(err) return err }
Just like in a for loop, it initializes a variable scoped only to the if statement.
This is an extremely convenient technique, yet there are almost no good alternatives in other languages. A common pattern in C is:
if( (fp = fopen( filne_name, "r" )) == NULL ){ printf( "%sファイルが開けません¥n", filne_name ); return -1; }
However, that's not very clean, and in the end you can't restrict the scope of the variable (fp) either.
You could achieve the same thing by extracting every if statement into its own method, but that isn't practical. Still, it's worth understanding the concept. It makes me shudder to think of not being able to limit the scope of i in a for loop (looking away from C).
Return Values
In Ruby, if is technically an expression and returns a value. When the condition is true, it returns the value of the last statement evaluated in the true branch.
You can take advantage of that to write something like this:
# if式の結果を変数に入れる result = if 条件 trueの場合に実行する文 else falseの場合に実行する文 end
Haskell similarly returns a value. Because Haskell is statically typed, if the return types don't match, it results in a compile error.
Variable Assignment Checking
I just explained that if expressions return values in some languages, but you can do something similar even in languages where if doesn't return a value. In Java, for example, it looks like this:
// if文の結果を変数に入れる int result; if (条件) { result = trueの場合に実行する文; } else { result = falseの場合に実行する文; } System.out.print(result);
What's interesting about Java is that code like the following triggers a compile error:
int result; if (条件) { result = trueの場合に実行する文; } else { falseの場合に実行する文; } System.out.print(result);
This fails to compile because result is not assigned a value in the else branch. There are broadly two ways to avoid this compile error.
One is to give result an initial value when declaring it. This works well when the if condition being true is strictly a special case: it stays at the default value normally and is overwritten inside the if in special cases. However, this approach relies on destructive assignment (mutation), which is generally discouraged because it makes it harder to track the variable's state.
The other is to assign a value in the else branch as shown originally. Even if the value is the same as an initial default, you avoid assigning to the variable multiple times, making its state easier to follow.
Condition Evaluation
This is about what counts as true and false in an if statement. From what I know, a common rule is that 0, null, and false are false, and everything else is true. In Go and Haskell, putting an expression that returns anything other than true/false in the condition causes a compile error.
Syntactic Sugar
There are various pieces of syntactic sugar (shorthand) for if statements, with the most famous ones probably being the ternary operator and postfix if statements.
Ternary Operator (The ? Operator)
Even in languages like C or Java where if statements don't return values, this lets you explicitly assign a return value on a single line. People often dislike it for hurting readability, but I think it's fine to use as long as it fits within about 80–100 characters. A staple for one-liners.
result = 条件 ? trueの場合に実行する文 : falseの場合に実行する文
Postfix if
This is syntactic sugar found in Ruby and CoffeeScript. You write it like this:
trueの場合に実行する文 if 条件
It has the advantage that when one branch is long, you don't have to read all the way to the closing end of the if statement. It also reduces nesting.
# before def do_something if condition method0 else method1 method2 method3 method4 method5 method6 end end # after def do_something return method0 if condition method1 method2 method3 method4 method5 method6 end
Techniques
Storing a Condition in a Variable
If you store the condition in a variable and reuse it, you can rewrite code like this, for example.
Also, giving a condition a meaningful name is always a good habit.
# before def do_something(a, b) if a > 0 && b > 0 && a > b c = a d = b else c = b d = a end puts "c:#{c}, d:#{d}" end # after def do_something(a, b) condition = a > 0 && b > 0 && a > b c = condition ? a : b d = condition ? b : a puts "c:#{c}, d:#{d}" end
Putting the Variable on the Right Side of the Equality Operator
This is a technique to trigger a compile error if you accidentally type assignment = instead of the equality operator ==. People used to write this often in C.
Because it's hard to read, nobody really does it anymore—and in languages that only allow booleans in conditions, it's an unnecessary worry.
Still, it's worth remembering that even today, mixing up == and = remains a relatively common bug.
if (1==a) { do_something }
Summary
As I wrote at the beginning, it really comes down to this: patterns that cause compile errors in static languages are better avoided—or used only in well-chosen places—in dynamic languages too.
To build that intuition, I think it's great stimulation for anyone who learned programming in a dynamic language to try learning a modern statically typed language at least once.
Also, it helps to be conscious of making the true and false branches of an if statement easy to compare side by side.
Disclaimer
I wrote this from memory without searching anything, so the code might have mistakes. Needless to say, I haven't run it either. As long as the idea gets across, that's what counts.