People are hating on this approach, but IMO the only reason people think this is bad or shows "unclear intent" is because it's new and they're unfamiliar with it.
It's extremely clear what this means, I don't know how you could get confused by this if you saw it in the code. Nobody has provided an example showing how this could be unclear.
Hard disagree, it's only more readable if your definition of readability is pinned to that of a beginner. As we become more knowledgeable our idea of readability should move with us.
Take this for example, beginners often don't know about ternaries:
const x = a ? b : c;
The more "readable" approach as you put it would be like this:
let x;
if (a) {
x = b;
else {
x = c;
}
Not only is this noisier and harder to parse for anyone more experienced but it's also opened up the need to track the mutability of the variable reference that didn't exist with the ternary approach.
The mutability can be easily avoided but introducing a function with an appropriate name.
function fun() {
if (a) {
return b;
} else {
return c;
}
}
const x = fun();
This is 100 % readable by anyone. And as you can't be sure everyone reading the code is on the same level as you, you should always prefer the version that is more readable by more people.
This is objectively less readable. A beginner would be confused why you're doing this instead of using mutability, and I'd be confused as to why you didn't just use a ternary.
Everyone who has ever written some code in any language possible, including Excel or Matlab, would understand it. While not everyone understand a ternary operator.
The only way you can make is less readable is if you are bad at naming functions and if you choose a wrong name for the function "fun". Be aware that the function can be a private method, you can move the function somewhere else or whatever. The point isn't there is a function just before the assignment. The point is you extract the code to the named function and then you can place the function anywhere else because it just became an implementation detail.
Understandability and readability are not synonymous. In this case you're optimising for the former at the expense of the latter.
I'm generally a fan of small functions as I lean heavily towards FP, but for something that can be viably solved by a ternary you're likely adding needless indirection.
I think it's both: more readable and more understandable. Because if you name the function right, you don't need to read the implementation at all. maximum(a, b) is more readable and more understandable than a > b ? a : b.
84
u/anon774 Nov 10 '20
People are hating on this approach, but IMO the only reason people think this is bad or shows "unclear intent" is because it's new and they're unfamiliar with it.
It's extremely clear what this means, I don't know how you could get confused by this if you saw it in the code. Nobody has provided an example showing how this could be unclear.