Why "if as expression not statement" is cool?

357 views Asked by At

I have heard few talks on modern programming languages like scala (and few other languages whose names I cannot remember right now), and often got the sense of excitement when the speakers were talking like: "if is an expression in our programming language, it returns value, WOW". So the question is, why an when if being an expression rather than a statement like in C is better?

2

There are 2 answers

0
vitalii On BEST ANSWER

It has to do with dealing with values instead of dealing with (re)assignments. Values are simple and (re)assignments are hard; Consider java where if construct is a statement, and also blocks {} are also sort of statements, and try is also kind of statement, and neither of them could return value:

Object someObject = null; // you'll have to scan through all 
// of the scope below to find out where `someObject` got assigned from

try {
  // ... and now imagine this if statements nested with try statements like
  // 20 times, and it's hard to  refactor them into multiple mehtods, 
  // because they are not logically connected

  if (someCondition) {
     someObject = <someValue>; 
  } else {
     someObject = <anotherValue>;
  }
} catch (Exception e) { ....};

compare with scala, where all those statements are actually expressions and can return values:

val someObject = try {
   if (someCondition) {
      "someResult" 
   } else {
     { "something else" }
   }
} catch { case Exception e => "someDefaultValue"; }

Now I argue that scala version is plainly simpler for understanding))) someObject is value so it got assigned one time, and I'm not bothered that somewhere below it got reassigned. I don't have to move variables outside if and try blocks just to keep them visible to the outside. And if I have a lot of nested if blocks, I still can deduce what result value will be at each level just by looking at it, while in java I need to keep whole method, and in fact execute it in my head to be able to deduce what top level variables got updated and when. BTW java has ?: operator but it is very limited compared to scala's if expression (mainly because you can't use brakets within).

0
Ingo On

It may be surprising for some, but there are languages that don't have "statements" at all. One example would be Haskell. In such circumstances there is no choice than having if expressions.

Note that any decent imperative language has if expressions, too. It's just called and written differently, like, for example:

cond ? "yes" : "no"

Incidentally, imperative languages short circuit such an expression, which is slang for lazy evaluation of the 2nd and 3rd expression (just like Haskell does it anyway).