7. Code Reviews & Branch Protection

Writing code is only half the battle. In professional software development teams, code quality is maintained through rigorous **Code Reviews** and enforced **Branch Protection Rules** on GitHub. In this chapter, we will learn how to review others' work and safeguard vital branches.

1. Reviewing a Pull Request

When a teammate opens a Pull Request and requests your review, you should go to the PR page and click the"Files changed" tab.

Here, GitHub displays a side-by-side or unified diff of all modifications. You can:

  • Add inline comments: Hover over any line of code and click the blue **"+"** icon to write a comment on a specific line of code.
  • Suggest Code Replacements: Click the Markdown "Suggestion" button in your comment field. You can rewrite the code line directly, allowing the PR author to apply your suggestion with a single click!
  • Start a Review: Group multiple comments together. Clicking "Start a review" keeps your comments in draft form until you submit the entire review.

2. Submitting Your Review

Once you have inspected all the files, click the green "Review changes" button in the top-right corner. You must choose one of three states:

Review StateDescriptionEffect on PR
CommentSubmit general feedback without explicitly approving or blocking the PR.Neutral. Keeps the PR in its current state.
ApproveSubmit feedback indicating you are happy with the changes and approve merging.Green light. The PR is now ready to merge (provided other conditions are met).
Request ChangesSubmit feedback detailing specific issues that **must** be fixed before merging.Red light. Merging is **blocked** until the author pushes updates and you approve.

3. Enforcing Quality with Branch Protection Rules

To prevent developers from accidentally pushing broken code directly to important branches (like main or production), you should configure **Branch Protection Rules** in GitHub settings:

  1. Go to your repository page and click the Settings tab.
  2. Click Branches in the left sidebar menu.
  3. Under "Branch protection rules", click "Add rule".
  4. Specify the target branch pattern (e.g., main).
  5. Enable key protective options:
    • Require a pull request before merging: Disables pushing directly to the branch. Developers must open a PR first.
    • Require approvals: Specify how many peer approvals (e.g., at least 1 or 2) are required before a PR can be merged.
    • Require status checks to pass: Ensures automatic test pipelines (like unit tests run in GitHub Actions) pass successfully before merging.
  6. Click Create.
Pro Tip: You can also choose **"Include administrators"** to prevent even repository owners and admins from bypassing these quality checks and pushing straight to main!