Comment by torginus
4 months ago
I've been dabbling in programming language design as of late, when trying to decide if including feature 'X' makes sense or not, with readability being the main focus I realized some old wisdom:
1 line should do 1 thing - that's something C has established, and I realized that putting conceptually different things on the same line destroys readability very quickly.
For example if you write some code to check if the character is in a rectangular area, and then turn on a light when yes, you can put the bounds check expressions on the same line, and most people will be able to read the code quickly - but if you also put the resulting action there, your code readability will suffer massively - just try it with some code.
That's why ternary expressions like a = condition? expr1: expr2 kinda controversial - they're not always bad, as they can encode logic about a single thing - if said character is friendly, turn the light color should be green, otherwise red - is a good example - but doing error handling there is not.
I haven't been able to find any research that backs this up (didn't try very hard tho), but I strongly believe this to be true.
A nice thing is that some other principles, like CQRS, can be derived from this, for example CQRS dictates that a function like checkCharacterInAreaThenSetLightState() is bad, and should be split up into checkCharacterInArea() and setLightState()
I'd perhaps generalize that to "it's useful to have visual grouping correlate with semantic grouping"; applies to separating words with spaces, sentences with punctuation, paragraphs with newlines, lines of code, UIs, and much more.
An important question for this also is what qualifies for "single thing"; you can look at a "for (int i = 0; i < n; i++) sum += arr[i]" as like 5 or more things (separate parts), 2 things (loop, body), or just one thing ("sum"). What array languages enable is squeezing quite a bit into the space of "single thing" (though I personally don't go as far as the popular k examples of ultra-terseness).
I'd say I'd decompose this into 2 'units'
- iterate through the array arr,
- sum its elements
of course, since C is a low level language, implementation details seep in there but those are the 2 major logical concepts that mentally can be quickly parsed as a single unit each.
Some languages allow reductions on collections, so the actual iteration becomes logically part of that single unit, so it might count as one, but I'd say that's the absolute upper bound of complexity you should stuff into a singlwe line.
The goal here is to make every statement conform to a template so that your brain quickly recognizes it and you can move on, rather than you having to break it apart bit by bit to figure out the goal.