Git hooks for enforcing code quality
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
Git hooks run scripts automatically at defined points in the commit and push workflow — they catch quality issues at the earliest possible moment, before code leaves the developer's machine.
Pre-commit hooks — the first quality gate
- A Spotless or Checkstyle pre-commit hook formats and validates code before the commit is created; a developer never sees a CI failure for an import ordering issue or a missing newline — it is fixed locally in seconds
- Pre-commit hooks run on the staged files only, so they are fast — a format check on changed files takes under a second versus a full Maven build
- The
.git/hooks/directory is not version-controlled; use thegit-build-hook-maven-pluginor Husky (for Node-based projects) to automatically configurecore.hooksPathduring the build so every developer gets the same hooks without manual steps
Commit-msg hooks — enforcing message conventions
- A
commit-msghook validates the commit message against Conventional Commits format (feat:,fix:,docs:) before the commit is recorded - Conventional Commits enables automated changelog generation and semantic version bumping — tools like
semantic-releaseparse commit history to determine whether the next version is a patch, minor, or major release - The hook runs immediately after the developer types the message, giving instant feedback rather than a CI reviewer comment hours later
The essential caveat: hooks are bypassable
- Any developer can skip hooks with
git commit --no-verify— hooks are a developer experience tool, not a security boundary - Mirror every hook check in the CI pipeline as an authoritative gate; the hook catches issues in 5 seconds locally instead of 20 minutes in CI, but CI is what actually enforces the standard
- This layered approach — fast local feedback plus authoritative CI gate — is the right mental model for all quality automation
Git hooks for enforcing code quality
Direct Answer
Git hooks are shell scripts that run automatically at specific points in the Git workflow. In Java projects, a pre-commit hook can run Checkstyle or Spotless to reject poorly formatted code before it is committed, a commit-msg hook can enforce Conventional Commits message format, and a pre-push hook can run the test suite. Manage hooks with core.hooksPath to share them across the team via the repository.
Check your understanding
Answer these without looking back at the article.
- How can a developer bypass a Git hook and when might that be legitimate?
- How would you integrate Checkstyle into a pre-commit hook for a large Java monorepo?
- What is Lefthook and how does it compare to Husky for managing Git hooks?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.