Good Code
The good version handles disqualifying cases first, which keeps the final return focused on the actual positive condition.
Lesson 02
Use early returns to keep exceptional cases out of the main path.
function canStartReview(user, pullRequest) {
// Guard clauses keep rejected cases out of the main path.
if (!user) {
return false;
}
if (pullRequest.isDraft) {
return false;
}
if (!pullRequest.reviewers.includes(user.id)) {
return false;
}
return pullRequest.filesChanged.length > 0;
}function canStartReview(user, pullRequest) {
// Nested branches make reviewers carry every condition at once.
if (user) {
if (!pullRequest.isDraft) {
if (pullRequest.reviewers.includes(user.id)) {
if (pullRequest.filesChanged.length > 0) {
return true;
}
}
}
}
return false;
}The good version handles disqualifying cases first, which keeps the final return focused on the actual positive condition.
The bad version reaches the same answer, but each nested branch makes reviewers hold more state in their heads before they can see the main rule.