Tests catch the bugs you thought to write a test for. Code review is supposed to catch the ones you didn't. In practice, most reviews drift toward style and readability because those are easy to see at a glance, while the bugs that actually cause outages a null that shouldn't exist, a race that only shows up under load, an assumption about input that held true until it didn't hide in plain sight inside code that looks completely reasonable.
This guide walks through twelve categories of bugs that routinely survive both unit tests and a casual review pass. For each one: a real example, why it slips through, the question a reviewer should be asking, and how to fix the implementation so the bug class doesn't come back.
1. Null / Undefined Values
Example (TypeScript):
function getDiscount(user: User): number {
return user.membership.tier === "gold" ? 0.2 : 0.1;
}
This compiles fine and passes a test where user.membership is always populated. It breaks the moment a user signs up but hasn't completed onboarding, and membership is undefined.
Why developers miss it: The type system says User has a membership field, so the code looks safe. But the type was probably written aspirationally, describing what the object looks like in the common case, not what the database or API can actually return. Tests are usually written against the happy-path fixture, which was built by someone who already knew what a "complete" user looks like.
What a reviewer should ask: "Is membership guaranteed to exist at this point in the code, or guaranteed by convention?" Those are different things. Ask where the object comes from if it's deserialized from JSON, a database row, or an external API response, assume it can be incomplete unless there's validation immediately upstream.
How to improve it:
function getDiscount(user: User): number {
const tier = user.membership?.tier;
return tier === "gold" ? 0.2 : 0.1;
}
Better still, push the validation to the boundary — validate the shape of User once, when it enters the system (API handler, deserialization layer), so everything downstream can trust the type without re-checking it everywhere. Optional chaining is a patch; a validated boundary is the actual fix.
2. Race Conditions
Example (Go):
var cache = map[string]int{}
func GetOrCompute(key string) int {
if val, ok := cache[key]; ok {
return val
}
val := expensiveCompute(key)
cache[key] = val
return val
}
Under a single goroutine, this is correct. Under concurrent load, two goroutines can both miss the cache, both call expensiveCompute, and both write to the map at the same time which in Go doesn't just risk overwriting a value, it can corrupt the map's internal state and crash the process (fatal error: concurrent map writes).
Why developers miss it: The code is correct in every test run, because tests almost always call the function sequentially. Race conditions are a property of timing, not logic, so reading the code top to bottom gives no signal that anything is wrong. The bug only exists when two things happen at the same moment, and that moment usually doesn't occur until production traffic exists.
What a reviewer should ask: "Can this function be called concurrently, and if so, what happens if two calls interleave at every possible line?" Specifically ask about shared mutable state maps, slices, counters, singletons anything that isn't local to the function.
How to improve it:
var (
cache = map[string]int{}
cacheMu sync.RWMutex
)
func GetOrCompute(key string) int {
cacheMu.RLock()
if val, ok := cache[key]; ok {
cacheMu.RUnlock()
return val
}
cacheMu.RUnlock()
val := expensiveCompute(key)
cacheMu.Lock()
cache[key] = val
cacheMu.Unlock()
return val
}
This still allows a rare double-compute (two goroutines both miss the cache before either writes), which is usually an acceptable tradeoff but it eliminates the crash. If double-computation itself is unacceptable, use sync.Once per key or a proper concurrent map (sync.Map, or a request-coalescing pattern like singleflight).
3. Incorrect Assumptions
Example (Python):
def apply_discount(price, discount_percent):
return price - (price * discount_percent / 100)
Looks fine. The assumption baked in silently: discount_percent is between 0 and 100. Nothing enforces that. Pass 150 and you get a negative price. Pass -10 and the customer gets charged more, and nobody notices because the number is still positive and plausible-looking.
Why developers miss it: The assumption isn't wrong from the author's point of view — of course a discount percent is 0–100, why would anyone pass anything else? That's exactly the trap: assumptions that feel too obvious to state out loud are the ones that never get validated, because nobody thinks of them as assumptions. They think of them as facts.
What a reviewer should ask: "What's the valid range for this input, and where is that enforced?" If the answer is "it's just never been anything else," that's not enforcement, that's luck.
How to improve it:
def apply_discount(price: float, discount_percent: float) -> float:
if not 0 <= discount_percent <= 100:
raise ValueError(f"discount_percent must be 0-100, got {discount_percent}")
return price - (price * discount_percent / 100)
The broader habit worth building: every time you write a comment explaining what a value "should" be, ask whether that "should" is actually checked anywhere, or just hoped for.
4. Boundary Conditions
Example (JavaScript):
function getPage(items, pageNumber, pageSize) {
const start = (pageNumber - 1) * pageSize;
return items.slice(start, start + pageSize);
}
Works for pageNumber = 1, 2, 3.... Call it with pageNumber = 0 and start becomes negative, and slice with a negative start counts from the end of the array — silently returning wrong data instead of erroring.
Why developers miss it: Boundary bugs live exactly at the edges most test suites don't bother visiting — page zero, an empty list, the last valid index, one past it. Developers write the test that matches the example they had in their head (page 1, page 2), and the off-by-one or below-zero case simply isn't part of that mental model.
What a reviewer should ask: "What happens at zero, at one, at the maximum, and at one past the maximum?" For anything involving indices, pagination, or loops, walk the boundary explicitly rather than trusting that "normal" inputs are the only inputs.
How to improve it:
function getPage(items, pageNumber, pageSize) {
if (pageNumber < 1 || pageSize < 1) {
throw new RangeError(`Invalid pagination: page=${pageNumber}, size=${pageSize}`);
}
const start = (pageNumber - 1) * pageSize;
return items.slice(start, start + pageSize);
}
A good habit: for any function that takes a numeric input, mentally test -1, 0, 1, and the largest plausible value before approving.
5. Timezone Issues
Example (Python):
from datetime import datetime
def is_expired(expiry):
return datetime.now() > expiry
If expiry was stored as a naive datetime in UTC, and the server running this happens to be in a different timezone (or gets migrated to one), datetime.now() returns local time, and comparisons silently produce wrong answers — sometimes for hours at a stretch, only near midnight, which makes the bug maddening to reproduce.
Why developers miss it: Timezone bugs are invisible in local development, where the developer's machine, the test runner, and the "expected" timezone often happen to align by coincidence. They surface only when infrastructure or user location diverges from that coincidence, which can be months after the code ships.
What a reviewer should ask: "Is this datetime timezone-aware, and is every value being compared using the same reference?" Ask specifically whether now()-style calls are UTC-aware, and whether stored timestamps were written with the same convention.
How to improve it:
from datetime import datetime, timezone
def is_expired(expiry: datetime) -> bool:
if expiry.tzinfo is None:
raise ValueError("expiry must be timezone-aware")
return datetime.now(timezone.utc) > expiry
The general rule: store and compare in UTC everywhere internally, convert to local time only at the point of display, and make naive datetimes a thing your code refuses to accept rather than silently tolerates.
6. Concurrency (Beyond Simple Races)
Example (Java):
public class OrderProcessor {
private int processedCount = 0;
public void process(Order order) {
// ... process order ...
processedCount++;
}
}
processedCount++ looks like one operation. It's actually read-modify-write, and under concurrent calls, increments can be lost — two threads read the same value, both increment, both write back the same result, and one increment vanishes.
Why developers miss it: The syntax hides the fact that it's three operations. Reviewers who don't specifically know this pattern read count++ and see "increment," full stop. It takes deliberate awareness of how the operation compiles to notice the gap.
What a reviewer should ask: "Is this field ever mutated by more than one thread, and if so, is the mutation atomic?" Any shared counter, shared collection, or shared flag in a multi-threaded context deserves this question by default.
How to improve it:
public class OrderProcessor {
private final AtomicInteger processedCount = new AtomicInteger(0);
public void process(Order order) {
// ... process order ...
processedCount.incrementAndGet();
}
}
More broadly: any time shared mutable state exists across threads, the reviewer's job is to ask not "is this correct" but "is this correct under interleaving" — a much harder and much more useful question.
7. Resource Leaks
Example (Python):
def read_config(path):
f = open(path)
data = f.read()
return json.loads(data)
If json.loads raises (malformed file), the file handle never gets closed. In a short script this barely matters. In a long-running service processing many files, this exhausts file descriptors over time and the process starts failing in ways that look completely unrelated to this function.
Why developers miss it: The function works in every manual test, because manual testing rarely exercises the failure path, and the consequence (fd exhaustion) is delayed and diffuse rather than immediate. By the time it manifests, it looks like an infrastructure problem, not a code problem.
What a reviewer should ask: "If this raises halfway through, does the resource it opened get released?" Applies to file handles, database connections, network sockets, locks, and anything else acquired with a corresponding release step.
How to improve it:
def read_config(path):
with open(path) as f:
data = f.read()
return json.loads(data)
The with statement guarantees the file closes even on exception. The reviewer habit worth building: any open, connect, or acquire call without a matching guaranteed release (context manager, try/finally) is worth a comment, even if today's code path happens not to fail.
8. Incorrect Error Handling
Example (JavaScript):
async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
return await res.json();
} catch (e) {
console.log("error fetching user");
return null;
}
}
Two separate problems here. First, fetch doesn't reject on HTTP error statuses — a 404 or 500 response resolves normally, so this catch block never fires for the errors most likely to occur, and the caller gets a "successfully parsed" error page as if it were user data. Second, when the catch block does fire, it swallows the actual error and returns null, indistinguishable from "user genuinely doesn't exist."
Why developers miss it: try/catch reads as "I've handled errors," which feels complete, even when the specific error path in question (non-2xx HTTP responses) doesn't route through catch at all. This is a gap in knowledge of the API's contract, not a gap in effort.
What a reviewer should ask: "What does this catch block actually catch, and what does the caller do with a null versus a real error?" Ask the author to name the specific failure modes (timeout, 404, 500, malformed JSON) and trace each one through the code by hand.
How to improve it:
async function getUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) {
if (res.status === 404) return null; // genuinely absent
throw new Error(`Failed to fetch user ${id}: ${res.status}`);
}
return res.json();
}
Errors that mean different things (not found vs. server failure vs. network failure) should produce different outcomes, not get flattened into the same null.
9. Authorization Mistakes
Example (Python / Flask-style):
@app.route("/documents/<doc_id>")
def get_document(doc_id):
doc = db.get_document(doc_id)
return jsonify(doc)
This checks that the requester is authenticated (assuming a decorator elsewhere handles that) but never checks that the requester is authorized to see this specific document. Any logged-in user can read any document by guessing or incrementing IDs.
Why developers miss it: Authentication and authorization get mentally bundled as "the user is logged in, so we're fine." They're separate concerns, and the code that checks the first often visually resembles code that would check the second, making the absence easy to overlook — there's no obviously missing line, just an implicit assumption that never got written down.
What a reviewer should ask: "This confirms who the user is — where does it confirm what they're allowed to access?" Ask this specifically for any endpoint or function that takes an ID from the caller and uses it to look something up.
How to improve it:
@app.route("/documents/<doc_id>")
@login_required
def get_document(doc_id):
doc = db.get_document(doc_id)
if doc is None or doc.owner_id != current_user.id:
abort(404) # 404, not 403 — don't confirm the document exists
return jsonify(doc)
Note the deliberate choice of 404 over 403 for a document the user doesn't own — returning 403 confirms the resource exists, which is itself a small information leak. Worth flagging explicitly in review, because it's the kind of detail that's easy to get "technically correct but subtly wrong."
10. State Inconsistencies
Example (TypeScript, frontend state):
function submitOrder(order: Order) {
setIsSubmitting(true);
api.submit(order).then(() => {
setIsSubmitting(false);
setOrderStatus("submitted");
});
}
If api.submit rejects, setIsSubmitting(false) never runs. The UI stays stuck in a submitting state forever, with no error shown and no way for the user to retry.
Why developers miss it: The happy path — request succeeds, state updates, done — is the path the developer clicks through while building the feature. The failure path requires deliberately breaking the network to observe, which nobody does unless they're specifically hunting for this bug.
What a reviewer should ask: "For every state transition this function makes on success, what resets that state on failure?" Look specifically for boolean flags (isLoading, isSubmitting) set to true with no corresponding false on the error branch.
How to improve it:
function submitOrder(order: Order) {
setIsSubmitting(true);
api.submit(order)
.then(() => {
setOrderStatus("submitted");
})
.catch((err) => {
setOrderStatus("error");
setErrorMessage(err.message);
})
.finally(() => {
setIsSubmitting(false);
});
}
finally guarantees the loading state resolves regardless of outcome — a small pattern that eliminates an entire category of "stuck spinner" bugs.
11. Unexpected Input
Example (Python):
def parse_amount(raw):
return float(raw.replace(",", ""))
Works for "1,000". Breaks — with an unhandled exception — for "", None, "1,000.50.25", or "$1,000". If this parses user-submitted form data, a malformed value takes down the whole request instead of producing a clear validation error.
Why developers miss it: The function was written against a specific expected format (probably copied from one real example during development), and every test added afterward tends to reuse variations of that same format, so the input space actually being tested is much narrower than the input space actually being received.
What a reviewer should ask: "Where does this input come from, and has anyone tried feeding it something adversarial or just malformed?" User-submitted strings, file contents, and third-party API responses should all be treated as untrusted until parsed and validated.
How to improve it:
def parse_amount(raw: str) -> float:
if not raw or not raw.strip():
raise ValueError("amount cannot be empty")
cleaned = raw.replace(",", "").replace("$", "").strip()
try:
return float(cleaned)
except ValueError:
raise ValueError(f"could not parse amount: {raw!r}")
The fix isn't handling every conceivable malformed string — it's converting an opaque crash into a clear, catchable error that the caller can act on.
12. Dependency Failures
Example (Node.js):
async function sendWelcomeEmail(user) {
await emailService.send(user.email, "welcome");
await db.markWelcomeEmailSent(user.id);
}
If emailService.send is slow or the email provider is down, this whole request — probably part of user signup — hangs or fails, even though sending a welcome email is not something that should be able to block account creation.
Why developers miss it: In development, third-party dependencies almost always respond quickly and successfully, so the code path where they don't simply never gets exercised before merge. The dependency's reliability characteristics in production are invisible from a local machine.
What a reviewer should ask: "If this dependency times out or errors, what happens to the rest of this flow — and should it?" Specifically ask whether a non-critical side effect (an email, an analytics call, a webhook) is allowed to block or fail a critical one (account creation, payment processing).
How to improve it:
async function completeSignup(user) {
await db.createUser(user);
// fire-and-forget, non-critical — failures shouldn't block signup
sendWelcomeEmail(user).catch((err) => {
logger.warn(`welcome email failed for ${user.id}`, err);
});
}
The broader question a reviewer should always ask about any external call: is this dependency in the critical path on purpose, or by accident?
The 15-Point Hidden-Bug Checklist
Keep this nearby during review. It's not exhaustive, but it catches the bugs that tests routinely miss.
Nulls: Can any value used here be
null/undefined/None, and is that path handled explicitly?Concurrency: Can this be called from more than one thread/process/request at once? What happens if two calls interleave?
Assumptions: What's assumed about the input (range, format, presence) that isn't actually enforced anywhere?
Boundaries: What happens at zero, one, the maximum, and one past the maximum?
Timezones: Is every datetime timezone-aware, and are all comparisons using the same reference?
Atomicity: Does any line that "looks like one operation" actually involve multiple steps under the hood?
Resource cleanup: If this raises halfway through, does everything it opened get closed/released?
Error specificity: Does the error handling distinguish between different failure causes, or flatten them into one generic outcome?
Authorization: Does this check not just who the user is, but what they're allowed to access?
State resets: For every state change on success, is there a corresponding reset or rollback on failure?
Untrusted input: Is any external, user-submitted, or third-party data trusted without validation?
Dependency criticality: If this external call fails or times out, should it be allowed to block the rest of the flow?
Idempotency: If this operation runs twice (retry, double-click, duplicate message), does it produce the same end state or a broken one?
Ordering: Does the code assume operations happen in a particular order that isn't actually guaranteed?
Silent failure: Is there any path where something goes wrong and the code carries on as if it didn't?
None of these require exotic tooling to catch — they require asking a slightly different question than "does this do what it's supposed to do." The question that finds hidden bugs is almost always "what happens when the thing I'm not testing for happens anyway."
About the author
- Codzee is building the future of AI-powered code reviews for modern engineering teams. We help developers review pull requests faster, improve code quality, and ship software with confidence. Codzee analyzes your code, highlights potential issues, suggests meaningful improvements, and delivers actionable feedback that fits your team's coding standards and workflow. Our mission is simple: make code reviews faster, smarter, and more collaborative without disrupting how developers work. Whether you're a startup shipping your first product or a growing engineering organization, Codzee helps reduce review bottlenecks, maintain consistent code quality, and improve developer productivity. At Codzee, we believe AI should support developers, not replace them. That's why we're building AI Code Review That Respects Your Team.
Comments
Join the discussionNo comments yet. Be the first to comment.




