tc39 / proposal-optional-chaining

https://tc39.github.io/proposal-optional-chaining/
4.94k stars 75 forks source link

concise or readable? which one would you choose? #47

Closed axetroy closed 6 years ago

axetroy commented 6 years ago
a?.b.c?.d(x?.y.z, m?.n)

// same with
func(argument1, argument2)

If the proposal become true.

maybe someone will write like this anti-human code. it's unreadable.

In fact, we can do this with lodash.get

Although increasing the amount of code, but it readable

const func = lodash.get(a, ["b", "c", "d"]);
const arg1 = lodash.get(x, ["y", "x"]);
const arg2 = lodash.get(m, ["n"]);

func && func(arg1, arg2);

Is it worth it?

Which one would you choose?

claudepache commented 6 years ago

I fail to see in what the “lodash” version is more readable than the “optional chaining” version?

AlMcKinlay commented 6 years ago

Any syntax can be used to be unreadable. The generic ?. is not, in itself unreadable.

a?.b.c?.d(x?.y.z, m?.n)

This is terrible, and if someone wrote code like this for my projects, I'd be asking them to rewrite it. You can abuse any syntax. But whatever the syntax is, this exact code would be unreadable.

The lodash code you wrote is changing what the underlying structure is.

const func = a?.b.c?.d;
const arg1 = x?.y.z;
const arg2 = m?.n;

func && func(arg1, arg2);

Now that they are written the same, how is the lodash one better? Is your first code example bad? Yes. Is that because of the syntax? No.

FranklinYu commented 6 years ago

Not the same thing. lodash.get(a, ["b", "c", "d"]) is only equivalent to a?.b?.c?.d; it lacks the functionality to specify required member.

claudepache commented 6 years ago

Which one would you choose?

  • [x] concise code
  • [x] readable code

Well, I’ve chosen concise and readable :-)

More seriously... @McInkay has adequately explained how to rewrite a?.b.c?.d(x?.y.z, m?.n) in a readable way without resorting to lodash.get. It is the responsibility of the programmer to keep a proper balance between readability and conciseness.

As I don’t foresee that this discussion will produce something fruitful for the Optional chaining proposal, I’m closing this issue.