r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

Show parent comments

1

u/lukashavrlant Dec 03 '20

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.

1

u/[deleted] Dec 03 '20

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.

1

u/lukashavrlant Dec 05 '20

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.

1

u/[deleted] Dec 05 '20

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.

1

u/lukashavrlant Dec 06 '20

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.

1

u/[deleted] Dec 06 '20

If you go far enough down that rabbit hole you'll find yourself needing sum types, something well beyond the understanding of your average beginner.