Hey, I have a code style question. The code style ...
# announcements
a
Hey, I have a code style question. The code style conventions say "prefer using single expressions". So what can be considered a single expression in Kotlin? I have my understanding but found today that my coworker has a different view and there is no definition in the docs on this as far as I can find. So would like to hear what do you consider a "single expression"
l
That looks like a bad rule as it's not clear, and there's no information about why you should prefer that unclear things.
d
Where does it say that? What are the two ideas of what an expression is?
a
The thing is in Kotlin almost everything is an expression as every fun can resolve to a value. So the co-worker is unsure of using try/catch as a single expreasion for readability purposes and doesn't understand why we should "prefer" that
I personally like single expression syntax very much but it is hard to convey that to someone when there is no reasoning mentioned why you should prefer it even if someone likes it or doesn't
l
To me, the rule is what you find more readable. This depends on the name of the function, its length, its complexity, the parameters… Only humans can judge that IMO, hard rules cannot work all the time, or you found a very complicated rule.
a
Unfortunately on a larger project you can't let everyone judge for themselves. Need for unification
l
Code reviews before merging in reference branches (i.e. non developer specific branches) can allow that. Through these reviews, "everyone" learns what "everyone" find readable enough given a kind of context.
a
On a project with 80 devs you can't really "learn" what everyone prefers, people need to have some style guidelines
l
To me, it's less a question of style, but rather a question of concensus regarding readability. I am working alone on most codebases, and using expression or block body is really based on if I can read it again easily afterwards. I avoid too long lines and too tight functions. But even for myself, 1 dev, I cannot find a hard rule for that. I can also change my mind about a piece of code, and that's okay. Change is inevitable. Trying to stop/avoid change is also a change. Is your team fighting over improperly used expression bodies? Or feels like some block bodies are overkill for some arguably short expressions?
a
I believe anything calculation or computation which takes less than one line should be a single expression. The moment you have flow, of a complex computation broken down into a chain reads better with a proper code block.