2 ms·
Or break them out into a function, then you can "short-circuit" with a return: int logic() { if (cond1) { return 1;
by jacobush 8y ago
Or break them out into a function, then you can "short-circuit" with a return:
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.
- spectramax 8y agoShort circuiting is poor for readability in my view because not only do you have to parse the syntax but you need to mentally walk through each case to understand what’s going on. 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.
- drawkbox 8y agoClear conditionals like this (or short circuiting) are very nice when it comes to merging. 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.