by jackdh · 5y ago · 0 comments
Sure in small cases this small ternary use is great! However too many times I've seen people chain them for far too many characters just to be "on one line".
We don't use one letter variable names anymore, so in the same reasoning why should we do the same to our code?
While is strictly more powerful than for, for is strictly more powerful than foreach, foreach is strictly more powerful than map.
And yet 95% of the time, the power in map is sufficient. Therefore 95% of the time you should use map. When you encounter a foreach, you should be expecting non-purity. When you encounter a while, you know that it's doing some recursive operation that requires that power. If you have junior members of the team writing while loops where maps would do the senior members of the team who understand the nuance will take 10x more time to understand that code.
The same applies to statements/code blocks vs expressions. If all you are doing is assigning one value and have no other side effects, and you can do so in a way that's not overly nested, you should use an expression. If you can't, we have the more powerful statement/block structure to fall back on.
[0]: https://blog.codinghorror.com/the-principle-of-least-power/
It was interesting to find out how HTML was designed from the start to be simple and not a programming language on purpose for this reason!
I strongly disagree with the author's idea that shorter is better. Clarity trumps conciseness. I'll admit that not enough conciseness can impact clarity, but there's ways and means to clean that up that don't involve clever code.
To test whether those statements are guiding principles, or merely ad-hoc justifications, I propose the following pylint rules based on those principles:
no-ternary-sugar:
Replace 'x if y else z' with '{True: lambda: x, False: lambda: z}[y]()'.
This is less concise, but improves clarity by using booleans explicitly,
and making the delayed evaluation of the results clear; both of which are
implicit in the 'if/else' syntactic sugar.
no-elif-sugar:
Replace:
if foo:
bar
elif baz:
quux
...
else:
foobar
With:
if foo:
bar
else:
if baz:
quux
else:
...
else:
foobar
This is less concise, but makes the branching structure clear, unlike the misleading
"flat" appearance of the 'elif' syntactic sugar.
no-special-case-patterns:
Replace:
if foo:
bar
else:
baz
With:
match foo:
case True:
bar
case False:
baz
'if/else' is syntactic sugar for pattern-matching a boolean, which is left implicit.
Explicit matching improves consistency with other use-cases, and makes the relationship
between branches and boolean clear, at the expense of conciseness.
(Also applies to single-armed 'if', which will only have a 'case True:').
Of course, the combination of no-elif-sugar and no-special-case-patterns would give extreme clarity like this: match foo:
case True:
bar
case False:
match baz:
case True:
quux
case False:
...
case False:
foobarEveryone has their own 'style' they like. It is usually not that big of a deal. It becomes a big deal if you get someone on the team who becomes obsessed with it, or someone who is always sloppy. Compact styles tend to be harder to decipher than simple ones. As when you are reading them they usually are not the same style context as all the other code around it. So it causes your brain to have to stop and figure it out. With python sometimes those compact styles actually run faster, so they can be handy to know about (test it though).
In java there is this thing where many will do things like blah = x().y().z(); Yet at any point in that chain something could crash out and return a null. It is compact for sure. But really is a pain to debug, but easy to read. Yet a lot of what is going on is burred in the 'middle' what if something in the middle is returning the wrong thing and the next thing in the chain happens to have the right method?
Compact styles can be easy to read sometimes if you know what that style is. You can also very easily introduce very subtle bugs. You can also convey the wrong meaning to the next poor soul that has to look at your code 3 years from now, 2 years after you left the company.
I use this style as sparingly as possible and fall towards verbose and spaced out code. I try to make it easy to read and broken down as best as possible. 6 months from now my tired brain will thank me.
For something like this example if I ended up with an if tree like that I would look at the underlying data structures. There is a data problem here and there probably would be a better way to do it.
I see this so often that I wrote a blog post about it http://chriswarbo.net/blog/2020-02-08-clever_code.html
tl;dr trying to make things smaller isn't "clever", it's code golf; often, "clever" solutions just-so-happen to end up small. Likewise, spreading logic over many lines can lose abstraction; we can end up lost in a tangle of bools, ints, etc. without seeing the bigger picture.
Getting that 'terse'/'readable' balance right can be tricky. Usually if some code is 'hard to read' it usually means it needs a bit of refactoring to shorten/length it up and make clear (with comments) what each bit is doing. You go drop something like duffs device into the middle of a parser you should put a comment on that. As not everyone has heard of it. If the code is going to be used a couple of times a year and if it takes an extra 15 seconds, so what. Comment it with 'hey this would be a good spot for duffs device?'. Most of the type of code I write these days runs so rarely and can take a bit of extra time. I am also working with jr devs who may or may not have read up on every cool trick. I am also playing with some code I got from the net. Some of these things have 5 page long functions, yep... totally lost in abstraction.