JavaScript

Lesson 02

Guard clauses

Use early returns to keep exceptional cases out of the main path.

Good Code

review-access.js
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;
}

Bad Code

review-access.js
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;
}

Review Notes

What to review

Good Code

The good version handles disqualifying cases first, which keeps the final return focused on the actual positive condition.

Bad Code

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.

Takeaways

  • Let the common path stay shallow by returning early for invalid inputs.