by DivisionSol · 7y ago · 0 comments
2. Yes, similar to my love my avoiding nesting, I too like avoiding indentation. Switch -> Case -> Statement+Break vs Object -> Key/Value.
3. I think this example dips a bit into the arcane. It's not that I can't read it, but you have a reduce starting with two arrays and some conditional logic. I don't often run into it, but I might try to think of where this can apply further.
4. Yes. Even though I love short concise code, I want the variables and function names to be clear to their meaning. When I read acceptable abstract code I expect the pieces to read like a set of instructions. Ideally the nicely named functions do what they say they do, and no more.
5. Hard pass. That ternary looks like a blob of characters and I have to think very hard about the logic going on. Not a... if b then a & b else a... I don't like picking on specific examples inside these kinds of posts, but on first pass:
if(!conditionA) return "Not A";
if(!conditionB) return "A";
return "A & B";
Probably give it a nice snappy function name so there isn't a bunch of conditional logic in the middle of a function, when I just want to know the state of two booleans, (with a caveat).The style I find works best is as follows. Note that alignment of the ? and : characters (and depending on the code style, the parentheses) is vital for the legibility of this style.
x = (condA) ? (trueA) : (falseA)
(condB) ? (trueB) : (falseB)
(condC) ? (trueC) : (falseC)
(condD) ? (trueD) : (falseD)
(condE) ? (trueE) : (falseE)
: (final case);
Mind you this has it's uses mostly in low level stuff but I find it a hell of a lot easier to read than a giant if else chain. x = (condA) ? (trueA) :
(condB) ? (trueB) :
(condC) ? (trueC) :
(condD) ? (trueD) :
(condE) ? (trueE) : (final case);
and the equivalent if/else chain should be: if (condA) {x = trueA }
elif (condB) {x = trueB }
elif (condC) {x = trueC }
elif (condD) {x = trueD }
elif (condE) {x = trueE }
else {x = (final case) }
In which case it doesn't really get you much readability-wise, since the formatting consistency appears in either case; the main benefit really is that ternary is an expression rather than a statementIt’s definitely superior, since it’s still less noise all around, but almost worthlessly so. And then the same pattern gets covered by switches too...
As for comparison against switches, I find that switches are very limited in a lot of languages (looking at you C/C++). The problem with the if else chain as well is that most code formatters seem to blow it up into the fully expanded form which kills readability.