if(cond1){
myVar = 1;
}
else if(cond2 && cond3){
myVar = 10;
}
else if(cond2 && !cond3){
myVar = 100;
}
else {
myVar = 4;
}
But when I encounter this kind of situations I have other problems than code formatting anyway:with 3 conditions you have 2^3 possibilities to check: are you really really sure (!cond1 && !cond2 && cond3) should give you defaultValue ? Do you really want 1 even if !cond2 ? etc...
When possible these conditions should be avoided in the first place (depending on context of course)
[0] https://stackoverflow.com/questions/14426366/what-is-an-idio...
if cond1 then
myVar = 1
else if cond2 and cond3 then
myVar = 10
else if cond2 and not cond3 then
myVar = 100
else
myVar = 4
end if
The VB.Net style also makes it easier to identify mismatched blocks because the "enders" are named differently. (One can also put the assignment on the same line as the conditional, but I generally don't recommend it.)Some may complain it's slightly verbose, but few if any will claim it's not clear.
myVar =
cond do
cond1 -> 1
cond2 && cond3 -> 10
cond2 && !cond3 -> 100
true -> 4
end
ML languages have similar constructs.That’s a problem. One I’ve seen all too often, but a problem, nonetheless.
myVar =
(!cond1) && (!cond2) && (!cond3) ? myValue_0 : // case 0 0 0 blabla
(!cond1) && (!cond2) && (cond3) ? myValue_1 : // case 0 0 1 bla
(!cond1) && (cond2) && (!cond3) ? myValue_2 : // case 0 1 0 blablabla
(!cond1) && (cond2) && (cond3) ? myValue_3 : // case 0 1 1
(cond1) && (!cond2) && (!cond3) ? myValue_4 : // case 1 0 0
(cond1) && (!cond2) && (cond3) ? myValue_5 : // case 1 0 1
(cond1) && (cond2) && (!cond3) ? myValue_6 : // case 1 1 0
(cond1) && (cond2) && (cond3) ? myValue_7 : // case 1 1 1
defaultValue; // uninteresting default (null, -1...)In case of more complex data generation you could use supplier pattern and combine it with strategy.
No need for any if else statements at all.
Sure it requires a lot more of work but is future proof and clear.
Foo(int x){return x+1} becomes Foo(Supplier x){return x() + 1}
Thats my cause.
(Does not make me any less right)
(You might consider reflecting on your tone and message. It presupposes bad faith on the other party, is dismissive and condescending, and you are probably less right than you think you are.)
It sounds interesting, that was all.
Yes, that's why for selections we usually use switch/case. But of course every programmer worth his money just knows that ?: is right associative and that '&&' is on precedence level 11 while '?:' is on 13. If that's not "clever code", I don't know what is...
I would hope every programmer worth their money are very comfortable with it, because chaining like this is a very common syntactic pattern in other people's code:
cond1 ? val1 : cond2 ? val2 : cond3 ? val3 : other
It is made less readable if you turn it into a right-nested mess of parentheses, so that is rarely seen.Just as nobody thinks of 'if..else' as right associative, but it actually is, and everyone uses that fact without thinking about it.
Same for '?:'. The associativity is just a formality that nobody thinks about.
> '&&' is on precedence level 11 while '?:' is on 13
On this I agree. I routinely put parentheses around complex conditions on the left side of ternaries for this reason.
I do remember the precedence, but I think leaving the parentheses out can raise a little doubt in the reader's mind, because it is common to use logical operators for control flow in languages like JavaScript, and control flow is at the same conceptual level as '?:'.
let x =
if cond1 { expr1 }
else if cond2 && cond3 { expr2 }
else { expr3 };
It’s more verbose this way (‘?’ Vs ‘else if’) but there’s no question of readability because it’s just if/else. You can format it however you like, and add statements into the blocks later if you need to, too.Rust also has the match statement, which is cleaner whenever your conditions are mutually exclusive.
Some would say top-level blocks returning the last value in the block is an anti-pattern, because functions which aren't meant to return a value end up leaking the value of the last thing called in the function, which might be another function, which called another function. Or it might be in various branches of an 'if', which aren't being examined for being an acceptable return value.
Perl does this, (like ECMAScript's 'do'), and while it's usefully concise sometimes, for API-level functions I think it's poor to accidentally leak values to the caller, that should never escape. The safe way to deal with this is an explicit void return at the end of API functions, but that's ugly and hard to remember.
I think JavaScript made the right choice in requiring explicit return from functions with blocks to return a value, with 'undefined' returned if nothing explicit is. Accidents are avoided.
Rust has taken an interesting approach of requiring a return type to be specified, which stops accidental leaks at least. Respect.
Rust will also only return the last expression in a block if it doesn't end in a semicolon. This can be a bit subtle when you're reading a long function, but combined with explicitly specified return types its hard to mess up while writing code. Because of the choice about that semicolon, its an explicit choice whether you want a block to evaluate into that expression or not. And for functions you can always just use an explicit return statement if you want anyway.
This will ignore the last result and return Nil instead:
sub foo ( $_ --> Nil ) {…}
This only works with literals, constants and Nil.If you specify a type instead, it only enforces that the result is of that type.
Keep in mind this is only a stage 0 proposal, and thus is not really part of the language. This is how statements behave when entered into the repl, e.g. the browser dev console.
Ruby has an if/else structure like the Rust/Lisp thing, as well. Tasty.
1. It's rare, so not many programmers have the pattern matching built up to read it easily.
2. Chained if/else statements have the benefit of indentations helping to show structure. The moment you add newlines to help show structure, a chain of ?:?:?:'s becomes much easier to read.
Most ?: expressions I see are uses inline, such as foo(a ? b : c). When you do that, you sometimes have to mentally unwind "ok so if a... what's a? why a? ok, so if a, then foo(b), else foo(c)". Putting the if(a) up front means you're already thinking about it by the time you get to the function call. So I reserve using ?: for when the difference between the two outcomes is minimal.
If it's very common where you work, then run, don't walk, away...
If you haven't encountered it often enough that it's familiar, than I think you probably don't read much code outside a small bubble.
The Linux kernel has another set of rules that differ in numerous ways (e.g. not wrapping single-line statements under a conditional in braces). Their rules are not strictly better or worse, just different and define their set of common idioms.
Another thing that the MD said to me during my interview was "code ought to be boring, testing can be interesting".
Besides switch/case do not apply to a mix of true/false conditions but to the different values of a single variable.
Funny :-) Thanks.
If you chain or nest them.
> Funny :-)
I'm glad I could brighten your day a little bit.
This language-design question is essentially a solved problem, but few new languages (outside the pure-ish functional ones) make the effort.
Trivial example in OCaml:
let imply v = match v with
(true,x) -> x
| (false,x) -> true;;
[0] https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora016... int logic()
{
if (cond1)
{
return 1;
}
if (cond2)
{
if (cond3)
{
return 10;
}
return 100;
}
// ...
return defaultValue;
}
Since it's a function, it's also apparent that you are only touching one variable: myVar = logic();
I love the ternary operator, but I find it's harder to step it in a debugger though.Traditional if/else conditionals express clarity by embedding the decision for myVar and visually show how it would be assigned in various cases.
As @hotBacteria said:
if(cond1){
myVar = 1;
} else if(cond2 && cond3){
myVar = 10;
} else if(cond2 && !cond3){
myVar = 100;
} else {
myVar = 4;
}
// Now return myVar
return myVar;
I’ll take this syntax over short circuiting any day.One liners and mammoth tertiaries that are too long can lead to conflicts and more problematic merges/diffs/etc.
One operation per line makes repos and merging, as well as blaming, reading and reviewing, easier to parse.
Style is a matter of taste, just like writing English: there are synonyms and idioms for every idea that you want to express, so use that freedom to choose the clearest communication. Like English, programming code is meant to communicate to other humans, so don't artificially limit your vocabulary in the name of consistency.
Consistency is a hobgoblin.
A foolish consistency is the hobgoblin of little minds.
The whole quote is important. Cutting parts out changes the meaning of the whole thing.
switch(true) {
cond1: return 1;
cond2 && cond3: return 10;
//etc
}
Not sure I'd recommend it but it works in a few languages :)Elixir has cond that does this nicely without resorting to strange switch statements:
https://elixir-lang.org/getting-started/case-cond-and-if.htm...
const pick = (param1, ...) => {
if (cond1) return 1;
if (cond2) return 10;
return 100;
};Or sometimes for multiple condition branches I use bitwise operators to create integer bit mask with couple of bits, then switch(), or array indexer, with all possible 4-8-16 values.
Your version is more error prone because contains more code than necessary. Note how it’s just “else” in original version, and manual negate statement, (cond2) && (!cond3), in your version. Easy to screw up when modifying the code at some later point. When you then need to replace cond3 with cond4, forget about second branch and the algorithm will break.
if a { v = 1 }
else if b && c { v = 10 }
else if b && !c { v = 100 }
else { v = d }The problem is that if one of the conditions changes, for example due to a variable renaming, you likely have to change the alignment on all lines.
Aside from being very tedious even if you're a lone coder, this creates noise in diffs that makes automatic merges fail much more frequently.
I mean, this whole thread reads like a holy war about code style - something the Go developers EXPLICITLY want to avoid because discussions about code style are a waste of time.
Everyone reading the above segment of code will have a different opinion on how to format it, while the real question should be "What does this code do". I mean this is highlighted in the preface of the presentation: "When you or I say that a foreign codebase is unreadable, what I think what we really mean is, I don’t understand it."
When I read this code I don't understand it, and it's not because of the formatting per se. Playing with the formatting does not make the purpose of the code clearer.
This whole thread where people argue about how to best format a structure is missing the point of the article completely.
?
This is not always possible, but when it is it's much easier to follow the flow of code and it reduces the number of lines of the condition tree.
enum situation { boring, clear, cleaver }
selector(context)
if context.proves(cond1)
return cleaver
if context.proves(cond2)
return clear
return boring
adjudicator(context)
switch( selector(context) )
cleaver: make_something_cleaver()
clear: make_something_clear()
default: make_something_stupid_simple()
Not completely the same situation, though, as there are no assignation here. For simple cases (`v = e0 ? e1 : e2`), ternary operator sure is fine, but for more complex cases, `some_var = selector(context)` tend to be a clearer path. That will also be better rendered in your API as the function fine documentation will have more chance to be extracted properly.Thus, it would be layed out like an else-if chain, but without the extra verbiage, particularly the repeated assignment.
(I can’t put in a proper example from my iPad, as it wants to capitalize all the lines, etc)
Disclaimer: Ruby was very influential to me in the mid 2000s, even if I never wrote any for pay. The if (else-if...) statement in Ruby works like a ternary chain in C based languages.
Combinations of if/else can seriously damage readability and maintainability.
I (all the time) face verbose code that pretend to be readable and that requires lots of attention just to find out you are setting a single variable across 10-20 lines.
Example:
* huge number of lines* not obvious (until we read all) that we setup a single variable
* combination of conditions difficult to trace for each given value
* high risk of forgetting cases...
Instead of
* one line per given value* operation on a single variable obvious
* match between conditions and values obvious
* high visibility on all the cases
* even more readable with proper vertical alignment
* a comment can be added on each line to document the case
[sorry for the multiple edits: I had a hard time getting { } properly display, they ate up the new lines]