I have read this link Should I return from a function early or use an if statement? and it triggered a conflict in my head. I agree that it looks nicer and cleaner and I guess that would be the way I would write it. But I remember that there was something saying that we should always check the the conditions under which we should DO stuff rather than trying to eliminate all the bad cases.

if (case_that_allows_to_do_stuff1 && case_that_allows_to_do_stuff2 ) {}

is preferable over

if (!this_case && !that_case && !oh_and_also_this_case) {}

Is this what I am saying related to the link above or is it a separate case?

有帮助吗?

解决方案

The answers in the linked question, when taken as a whole, amount to it depends. Often having a single point of return is preferable, but there are times when early return greatly simplifies code. The mistake would be relying on a rote rule rather than focusing on good design.

The same applies in your case. There is no reason to always prefer checking whether something is true rather than check whether it is false. You need to think about what constitutes good design in any specific case.

if (!something) can be slightly less clear than if (something), particularly when checking more than a single condition. However, refactoring the code so that all your conditionals check for truth may make the code much less understandable in practice.

As a starting point, I would try to write it in the way that I would intuitively describe what the function is doing.

其他提示

we should always check the the conditions under which we should DO staff rather than trying to eliminate all the bad cases.

No.

If that were true, there would be no such thing as Guard Clauses, and guard clauses are considered a best practice.

That said, guard clauses look a bit different in Javascript than in some other programming languages, due to the presence of first-class functions and the unique role that function scoping has in Javascript.

Further Reading
Guard and Default operators in Javascript
No ifs…alternatives to statement branching in JavaScript

The cases are related. However, neither the first nor the second approach is bad.

In an ideal scenario, your functions are no longer than a few lines, which in the end means it does not really matter whether you use the first or the second approach, as both of them are very easy to read.

The problem occurs, when you end up with a function which is really long, which usually means something isn't right in your code in the first place and should be probably refactored.

As long as you keep functions separated, simple, it's mostly up to you whether to use an early return statement or do a guard if block.

I, personally, like an early return better, because when you leave the function, you don't need to scan the rest of it wondering, whether another piece of code does not alter the result.

许可以下: CC-BY-SA归因
scroll top