4 ms·
You're completely missing the point. The switch expression is exactly that, an expression. It can be used wherever you can use an expression. This is fundamenta
by dtech 9y ago
You're completely missing the point. The switch expression is exactly that, an expression. It can be used wherever you can use an expression. This is fundamental to programming languages and especially in functional programming languages where it is a requirement of everything in the language.
You can use logging/side effect in it. You can not assign it to a variable, all valid in Java.
Consider the if expression (ternary ?: operator in Java). In most modern languages (e.g. Scala, Kotlin, Rust) there is no ternary operator, and only an if-expression:
int value = if(something) 1 else 2
According to you, this is wrong, but it isn't, you can still use it as a statement:
if(something) {
doThis()
} else {
doThat()
}
Just like you can have a statement (line) with just "1+1" or "doThis()", you can have a statement of just an if-expression.
And you can also add side-effect (logging) withing expressions:
int value = if(something) {
log("Uh oh");
-1
} else {
1
}
Making a language construct an expression is the complete opposite of tying it to a particular use-case, it's giving it the ultimate flexibility because you can use expressions everywhere.
- makecheck 9y agoI’m not debating why expressions are part of languages. I’m saying that I shouldn’t have to tear apart half the code just to make a change. And there are very simple examples of that problem, right in the article: 1. Allowing the entire switch expression to bind to the same assignment makes it difficult to maintain when adding a case that will not perform that assignment. Now, instead of adding one line, you’re tearing apart half the block and trying to find a way to make equivalent new code. 2. Even adding a single line to a case may be impossible without rewriting the case. Given some 'case "Bar" -> 2;', the maintainer has to redo the entire thing: rewrite it as 'case "Bar":' with a colon, add 'break 2;' to preserve original behavior, and then add their stuff. That’s just broken; it won’t even produce a clean "diff" because you’re “changing” lines that don’t have anything to do with your new code. And you can bet at some point that somebody may just plain forget to add back the "break" when rewriting the expression needlessly, introducing a bug.