The Quest Begins (The "Why")
Picture this: I’m staring at a pull request that touches twenty‑seven files, adds a new authentication flow, tweaks the UI, refactors a utility library, and somehow also fixes a typo in the README. The description is a novel, the diff is a wall of red and green, and I have exactly twenty minutes before my next meeting. I start scrolling, hoping to find the “important” bits, but after ten minutes I’m lost in a sea of changes, questioning whether that weird variable name is a bug or just my tired eyes playing tricks. I hit “Approve” half‑heartedly, hoping CI will catch whatever I missed. Two days later, a production bug surfaces because a side‑effect in that utility refactor slipped through. The team groans, the incident report writes itself, and I’m left wondering—how did we let this happen?
That moment was my dragon. Not a fire‑breathing beast, but the creeping feeling that big, unfocused PRs are silently eroding code quality. I realized I wasn’t just reviewing code; I was gambling with the stability of everything we ship.
The Revelation (The Insight)
The treasure I uncovered wasn’t a fancy new tool or a secret framework—it was a simple shift in mindset: keep every pull request small, focused, and tied to a single logical change. When a PR does one thing well, reviewers can actually see what’s happening, ask meaningful questions, and spot subtle bugs before they escape into the wild. It’s like handing someone a flashlight instead of a floodlight; they can examine the details without being blinded.
Why does this work?
- Cognitive load drops – a reviewer can hold the entire change in their head.
- Context stays intact – the commit message, tests, and description all point to the same goal.
- Feedback loops tighten – small changes get reviewed faster, meaning you iterate quicker.
- Regression risk shrinks – fewer moving parts mean fewer places for a bug to hide.
Adopting this habit didn’t just improve my review speed; it changed how I write code. I started thinking in increments: “What’s the smallest piece I can deliver that still provides value?” That question became my compass, steering me away from sprawling, risky commits and toward clean, testable steps.
Wielding the Power (Code & Examples)
The Trap: The Monolithic PR
Let’s say we’re adding a “password reset” feature. A typical (and dangerous) approach might look like this:
+ // src/services/authService.js
+ export async function requestPasswordReset(email) {
+ const user = await db.findUserByEmail(email);
+ if (!user) throw new Error('User not found');
+ const token = crypto.randomBytes(32).toString('hex');
+ await db.storeResetToken(user.id, token);
+ await emailService.sendResetEmail(email, token);
+ }
+
+ // src/routes/authRoutes.js
+ router.post('/request-reset', async (req, res) => {
+ try {
+ await requestPasswordReset(req.body.email);
+ res.status(200).json({ message: 'If the email exists, a reset link was sent.' });
+ } catch (err) {
+ res.status(400).json({ error: err.message });
+ }
+ });
+
+ // src/components/ResetRequestForm.jsx
+ import { useState } from 'react';
+ export default function ResetRequestForm() {
+ const [email, setEmail] = useState('');
+ const [loading, setLoading] = useState(false);
+ const handleSubmit = async e => {
+ e.preventDefault();
+ setLoading(true);
+ try {
+ await fetch('/api/auth/request-reset', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ email })
+ });
+ alert('Check your inbox!');
+ } catch {
+ alert('Something went wrong.');
+ } finally {
+ setLoading(false);
+ }
+ };
+ return (
+ <form onSubmit={handleSubmit}>
+ <input
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ placeholder="Your email"
+ disabled={loading}
+ />
+ <button type="submit" disabled={loading}>
+ {loading ? 'Sending...' : 'Send Reset Link'}
+ </button>
+ </form>
+ );
+ }
+
+ // src/styles/resetRequest.css
+ .reset-form { max-width: 300px; margin: 2rem auto; }
+ .reset-form input { width: 100%; padding: 0.5rem; }
+ .reset-form button { width: 100%; padding: 0.75rem; background: #0066ff; color: white; border: none; cursor: pointer; }
+ .reset-form button:disabled { background: #cccccc; cursor: not-allowed; }
+
+ // __tests__/authService.test.js
+ import { requestPasswordReset } from '../src/services/authService';
+ jest.mock('../src/db');
+ jest.mock('../src/emailService');
+
+ describe('requestPasswordReset', () => {
+ it('should generate a token and send an email', async () => {
+ db.findUserByEmail.mockResolvedValue({ id: 1 });
+ db.storeResetToken.mockResolvedValue();
+ emailService.sendResetEmail.mockResolvedValue();
+ await requestPasswordReset('test@example.com');
+ expect(emailService.sendResetEmail).toHaveBeenCalledWith('test@example.com', expect.any(String));
+ });
+ });
All of this lives in one PR. The reviewer must juggle backend logic, routing, React UI, CSS, and tests—all at once. If something is off in the CSS, they might miss it while focusing on the token generation. If the test mock is wrong, they might not notice until the build fails hours later. The result? A higher chance of subtle bugs slipping through, longer review times, and a feeling of “I just approved a monster.”
The Victory: The Focused PR
Now break that same feature into four tiny, logical PRs:
PR 1 – Backend service only
+ // src/services/authService.js
+ export async function requestPasswordReset(email) {
+ const user = await db.findUserByEmail(email);
+ if (!user) throw new Error('User not found');
+ const token = crypto.randomBytes(32).toString('hex');
+ await db.storeResetToken(user.id, token);
+ await emailService.sendResetEmail(email, token);
+ }
+
+ // __tests__/authService.test.js
+ import { requestPasswordReset } from '../src/services/authService';
+ jest.mock('../src/db');
+ jest.mock('../src/emailService');
+
+ describe('requestPasswordReset', () => {
+ it('should generate a token and send an email', async () => {
+ db.findUserByEmail.mockResolvedValue({ id: 1 });
+ db.storeResetToken.mockResolvedValue();
+ emailService.sendResetEmail.mockResolvedValue();
+ await requestPasswordReset('test@example.com');
+ expect(emailService.sendResetEmail).toHaveBeenCalledWith('test@example.com', expect.any(String));
+ });
+ });
PR 2 – API route
+ // src/routes/authRoutes.js
+ const express = require('express');
+ const router = express.Router();
+ const { requestPasswordReset } = require('../services/authService');
+
+ router.post('/request-reset', async (req, res) => {
+ try {
+ await requestPasswordReset(req.body.email);
+ res.status(200).json({ message: 'If the email exists, a reset link was sent.' });
+ } catch (err) {
+ res.status(400).json({ error: err.message });
+ }
+ });
+
+ module.exports = router;
+
+ // __tests__/authRoutes.test.js
+ const request = require('supertest');
+ const app = require('../app');
+ jest.mock('../services/authService');
+
+ it('returns 200 for valid email', async () => {
+ requestPasswordReset.mockResolvedValue();
+ const res = await request(app)
+ .post('/api/auth/request-reset')
+ .send({ email: 'test@example.com' });
+ expect(res.status).toBe(200);
+ });
+
+ it('returns 400 when service throws', async () => {
+ requestPasswordReset.mockRejectedValue(new Error('Bad'));
+ const res = await request(app)
+ .post('/api/auth/request-reset')
+ .send({ email: 'test@example.com' });
+ expect(res.status).toBe(400);
+ });
PR 3 – React component
+ // src/components/ResetRequestForm.jsx
+ import { useState } from 'react';
+ export default function ResetRequestForm() {
+ const [email, setEmail] = useState('');
+ const [loading, setLoading] = useState(false);
+ const handleSubmit = async e => {
+ e.preventDefault();
+ setLoading(true);
+ try {
+ await fetch('/api/auth/request-reset', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ email })
+ });
+ alert('Check your inbox!');
+ } catch {
+ alert('Something went wrong.');
+ } finally {
+ setLoading(false);
+ }
+ };
+ return (
+ <form onSubmit={handleSubmit}>
+ <input
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ placeholder="Your email"
+ disabled={loading}
+ />
+ <button type="submit" disabled={loading}>
+ {loading ? 'Sending...' : 'Send Reset Link'}
+ </button>
+ </form>
+ );
+ }
+
+ // __tests__/ResetRequestForm.test.jsx
+ import { render, screen, fireEvent } from '@testing-library/react';
+ import ResetRequestForm from './ResetRequestForm';
+ import userEvent from '@testing-library/user-event';
+
+ it('calls fetch with email on submit', async () => {
+ const fetchMock = jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true });
+ render(<ResetRequestForm />);
+ await userEvent.type(screen.getByPlaceholderText(/your email/i), 'test@example.com');
+ await userEvent.click(screen.getByRole('button', { name: /send reset link/i }));
+ expect(fetchMock).toHaveBeenCalledWith('/api/auth/request-reset', expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({ email: 'test@example.com' })
+ }));
+ fetchMock.mockRestore();
+ });
PR 4 – Styling (optional, if you keep CSS separate)
+ // src/styles/resetRequest.css
+ .reset-form { max-width: 300px; margin: 2rem auto; }
+ .reset-form input { width: 100%; padding: 0.5rem; }
+ .reset-form button { width: 100%; padding: 0.75rem; background: #0066ff; color: white; border: none; cursor: pointer; }
+ .reset-form button:disabled { background: #cccccc; cursor: not-allowed; }
Each PR is
Top comments (0)