Your Code Works, That Does Not Mean It Is Correct
Earlier in my career, I spent years writing code that passed every test I threw at it. I thought that meant it was correct. Features were shipping on time, tests passed, code reviews went smoothly, nothing I deployed caused an incident that anyone traced back to me. I thought I was writing correct code. I was writing code that worked under the conditions I had tested, which is a different thing, and I did not fully understand the difference until an incident made it concrete.
The first time was a counter in a Java service. A shared integer, incremented on every request, used to track throughput metrics. It worked perfectly in development. Under real traffic, with forty threads hitting the same endpoint simultaneously, the counter started drifting. After an hour it was off by thousands. I spent two hours convinced the issue was somewhere in the reporting logic before I understood what count++ actually compiles to: three separate CPU instructions, not one. Read the value, add one, write the result back. Two threads reading before either writes produce the same incremented value. One update disappears. The code looked correct. The tests were green. The behaviour under concurrent load was silent data corruption.
The second time was in Python. A function that returned the last N items from a list, written quickly, tested with typical inputs. Under production load, a specific request sent a value of N larger than the list itself. Python’s negative indexing silently returned the entire list rather than raising an error. No exception, no log line, no indication that anything went wrong. The caller received more data than it asked for and processed it as if it were correct. That bug ran undetected for six weeks.
The third time was in Rust, which I had started learning partly because I believed its compiler would catch this class of mistake. A recursive parser that worked flawlessly against every test input crashed in production forty seconds after deployment with a stack overflow. The compiler had caught every memory safety issue I threw at it. It had nothing to say about the runtime depth of a call stack, which is not a type error.
Each of these bugs shared the same structure: code that worked correctly under the inputs and conditions I tested, and broke under inputs and conditions I had not thought to test. The compiler did not catch them. The test suite did not catch them. They waited for production, where the data is real and the load is real and the edge cases you did not consider arrive in whatever order they feel like.
Working code handles the inputs you tested. Correct code handles the inputs you did not think to test. Understanding the specific categories where they diverge is what changed how I write tests, how I think about concurrency, and how I read error handling in code reviews. What follows is those categories, illustrated in Rust, Java, and Python, because the languages differ in which failures they catch automatically and which ones they hand back to you expecting you to have thought about it.
The race condition that only appears when the system is under pressure
In development, your service handles one request at a time or ten requests spread across a few seconds. In production, it handles a thousand requests arriving in the same fifty milliseconds from users who do not coordinate with each other. The code that worked fine in development is now running in a dozen threads simultaneously, and the assumptions that held when things were sequential are quietly being violated.
The classic form is a read-modify-write operation on shared state without adequate synchronisation. In Java, this looks like:
// Looks fine. Passes every single-threaded test you write.
public class Counter {
private int count = 0;
public void increment() {
count++; // read count, add 1, write count back
}
public int get() {
return count;
}
}
// Looks fine. Passes every single-threaded test you write.
public class Counter {
private int count = 0;
public void increment() {
count++; // read count, add 1, write count back
}
public int get() {
return count;
}
}
count++ is not atomic. It compiles to three separate CPU instructions: read the current value into a register, add one, write the result back. If two threads both read the value before either writes, they both compute the same incremented value and write it back. One increment is lost. Under low concurrency this almost never happens. Under high concurrency it happens constantly and the counter drifts further and further from the true value. Every test passes because tests run on a single thread or with minimal concurrency that does not trigger the timing window.
The correct version uses AtomicInteger, which performs the increment as a single atomic hardware instruction:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private final AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet(); // single atomic instruction, no race
}
public int get() {
return count.get();
}
}
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private final AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet(); // single atomic instruction, no race
}
public int get() {
return count.get();
}
}
In Python, the GIL reduces the likelihood of certain races in CPython by allowing only one thread to execute Python bytecode at a time, but it is not a substitute for proper synchronisation. It does not protect you across I/O operations, across multiple processes, or in any Python runtime that does not have a GIL. Code that relies on the GIL for correctness is code that will break when the GIL is removed, which is exactly what Python 3.13’s experimental no-GIL mode is doing.
Rust’s ownership system prevents data races at compile time. If you try to share mutable state across threads without synchronisation, the code does not compile:
use std::thread;
fn main() {
let mut count = 0;
let handle = thread::spawn(|| {
count += 1; // error: cannot borrow `count` as mutable
// because it is also borrowed as immutable
});
println!("{}", count);
handle.join().unwrap();
}
use std::thread;
fn main() {
let mut count = 0;
let handle = thread::spawn(|| {
count += 1; // error: cannot borrow `count` as mutable
// because it is also borrowed as immutable
});
println!("{}", count);
handle.join().unwrap();
}
The correct Rust version uses Arc<Mutex<T>> or atomic types, the same conceptual solution as Java’s AtomicInteger, but the compiler forces you to reach for it. You do not have the option of shipping the broken version:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let count = Arc::new(Mutex::new(0));
let count_clone = Arc::clone(&count);
let handle = thread::spawn(move || {
let mut c = count_clone.lock().unwrap();
*c += 1;
});
handle.join().unwrap();
println!("{}", count.lock().unwrap());
}
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let count = Arc::new(Mutex::new(0));
let count_clone = Arc::clone(&count);
let handle = thread::spawn(move || {
let mut c = count_clone.lock().unwrap();
*c += 1;
});
handle.join().unwrap();
println!("{}", count.lock().unwrap());
}
This is the category where Rust is genuinely, provably better than Java and Python. Not as a marketing claim, as a type system guarantee. The other categories below are language-agnostic.
The integer overflow that only happens with specific input sizes
Every integer type has a range. When a value exceeds that range, something happens, and what happens depends on the language and whether you are running in debug or release mode.
In Python, integers have arbitrary precision. They grow to accommodate any value. This particular failure mode does not exist in pure Python, which is one of the things Python gets genuinely right. The cost is performance: arbitrary precision integers are slower than fixed-width integers because they require heap allocation and more complex arithmetic.
In Java, integer overflow wraps silently. The value goes past the maximum, wraps to the minimum, and continues from there. The JVM does not throw an exception. Your code does not crash. It produces a wrong answer, quietly, with no indication that anything went wrong:
int maxValue = Integer.MAX_VALUE; // 2,147,483,647
int wrapped = maxValue + 1; // -2,147,483,648 — silent wrap
System.out.println(wrapped); // prints -2147483648, no error
int maxValue = Integer.MAX_VALUE; // 2,147,483,647
int wrapped = maxValue + 1; // -2,147,483,648 — silent wrap
System.out.println(wrapped); // prints -2147483648, no error
This caused a real incident in 2006 when a binary search implementation in the Java standard library used (low + high) / 2 to calculate the midpoint. When low and high were both large enough, their sum wrapped to a negative number, the midpoint became negative, and the array access threw an ArrayIndexOutOfBoundsException. The correct version is low + (high - low) / 2, which cannot overflow for valid array indices. The bug had existed in the library for nearly a decade before Joshua Bloch documented it in a widely-read blog post.
In Rust, integer overflow panics in debug mode and wraps in release mode. Neither behaviour is ideal, but Rust gives you explicit methods to choose the behaviour you actually want:
fn main() {
let max: i32 = i32::MAX;
// debug mode: panics with 'attempt to add with overflow'
// release mode: wraps silently (same as Java)
// let wrapped = max + 1;
// explicit wrapping — you are choosing this behaviour consciously
let wrapped = max.wrapping_add(1);
println!("{}", wrapped); // -2147483648
// explicit checked — returns None on overflow
let checked = max.checked_add(1);
println!("{:?}", checked); // None
// explicit saturating — stops at the maximum value
let saturated = max.saturating_add(1);
println!("{}", saturated); // 2147483647 — stays at max
}
fn main() {
let max: i32 = i32::MAX;
// debug mode: panics with 'attempt to add with overflow'
// release mode: wraps silently (same as Java)
// let wrapped = max + 1;
// explicit wrapping — you are choosing this behaviour consciously
let wrapped = max.wrapping_add(1);
println!("{}", wrapped); // -2147483648
// explicit checked — returns None on overflow
let checked = max.checked_add(1);
println!("{:?}", checked); // None
// explicit saturating — stops at the maximum value
let saturated = max.saturating_add(1);
println!("{}", saturated); // 2147483647 — stays at max
}
Rust’s default behaviour in release mode is the same as Java’s: silent wrap. What differs is that Rust forces you to be explicit about which overflow behaviour you want when you reach for one of the deliberate variants. checked_add returning None is correct for a function where overflow represents an error. wrapping_add is correct for hash functions and cyclic counters. saturating_add is correct for volume controls and progress bars. In Java you get one behaviour whether you want it or not.
The floating point error that only accumulates over time
Floating point arithmetic is not exact. Every developer knows this in the abstract. Most developers underestimate how much it matters in practice.
The specific failure mode is that small rounding errors accumulate over repeated operations. A single 0.1 + 0.2 producing 0.30000000000000004 is harmless. Ten thousand transactions each rounded slightly incorrectly is a financial discrepancy that someone will eventually notice and trace back to your code.
<button data-code="# Python
total = 0.0
for _ in range(10_000):
total += 0.1
print(total) # 1000.0000000001588 (not 1000.0)
print(total == 1000.0) # False
// Java — same problem
double total = 0.0;
for (int i = 0; i
# Python
total = 0.0
for _ in range(10_000):
total += 0.1
print(total) # 1000.0000000001588 (not 1000.0)
print(total == 1000.0) # False
// Java — same problem
double total = 0.0;
for (int i = 0; i < 10_000; i++) {
total += 0.1;
}
System.out.println(total); // 999.9999999999766
System.out.println(total == 1000.0); // false
// Rust — same problem, same hardware, same IEEE 754 standard
let mut total: f64 = 0.0;
for _ in 0..10_000 {
total += 0.1;
}
println!("{}", total); // 1000.0000000001588
println!("{}", total == 1000.0); // false
# Python
total = 0.0
for _ in range(10_000):
total += 0.1
print(total) # 1000.0000000001588 (not 1000.0)
print(total == 1000.0) # False
// Java — same problem
double total = 0.0;
for (int i = 0; i < 10_000; i++) {
total += 0.1;
}
System.out.println(total); // 999.9999999999766
System.out.println(total == 1000.0); // false
// Rust — same problem, same hardware, same IEEE 754 standard
let mut total: f64 = 0.0;
for _ in 0..10_000 {
total += 0.1;
}
println!("{}", total); // 1000.0000000001588
println!("{}", total == 1000.0); // false
This is not a language problem. It is a hardware problem. IEEE 754 floating point is implemented in silicon and all three languages use it. The solution is the same regardless of language: never use floating point for values where exact decimal arithmetic matters.
Money is the obvious example. Use BigDecimal in Java, Python’s decimal module, or an integer representing the smallest currency unit in any language.
<button data-code="// Java — correct for money
import java.math.BigDecimal;
BigDecimal total = BigDecimal.ZERO;
BigDecimal increment = new BigDecimal("0.1"); // note: string constructor, not double
for (int i = 0; i
// Java — correct for money
import java.math.BigDecimal;
BigDecimal total = BigDecimal.ZERO;
BigDecimal increment = new BigDecimal("0.1"); // note: string constructor, not double
for (int i = 0; i < 10_000; i++) {
total = total.add(increment);
}
System.out.println(total); // 1000.0
System.out.println(total.compareTo(new BigDecimal("1000.0")) == 0); // true
// Java — correct for money
import java.math.BigDecimal;
BigDecimal total = BigDecimal.ZERO;
BigDecimal increment = new BigDecimal("0.1"); // note: string constructor, not double
for (int i = 0; i < 10_000; i++) {
total = total.add(increment);
}
System.out.println(total); // 1000.0
System.out.println(total.compareTo(new BigDecimal("1000.0")) == 0); // true
The string constructor matters here. new BigDecimal(0.1) takes a double as input and the double is already imprecise before BigDecimal ever sees it, so you get 0.1000000000000000055511151231257827021181583404541015625 rather than 0.1. The string constructor new BigDecimal("0.1") parses the exact decimal representation you wrote, which is what you want. This is a common interview question and also a common production bug.
// Rust — correct for money: use integer arithmetic
let mut total_pence: i64 = 0; // store in smallest unit
for _ in 0..10_000 {
total_pence += 10; // 10 pence = £0.10
}
println!("£{:.2}", total_pence as f64 / 100.0); // £1000.00 — only convert for display
// Rust — correct for money: use integer arithmetic
let mut total_pence: i64 = 0; // store in smallest unit
for _ in 0..10_000 {
total_pence += 10; // 10 pence = £0.10
}
println!("£{:.2}", total_pence as f64 / 100.0); // £1000.00 — only convert for display
The test that catches this is also the test almost nobody writes: run the operation ten thousand times and assert the result equals the expected value exactly. One iteration passes. Ten thousand iterations fails. A test suite that only checks single operations will never find this.
The off-by-one error that only triggers on empty or maximum input
Off-by-one errors are the oldest category in this list and the one that still causes the most incidents relative to how simple they look. The test that finds them is also the test developers most often forget to write: test the boundary, not just the middle.
def get_last_n(items, n):
# Works for all typical inputs.
# Fails silently when n equals or exceeds the length of items.
return items[len(items) - n:]
data = [1, 2, 3, 4, 5]
print(get_last_n(data, 3)) # [3, 4, 5] — correct
print(get_last_n(data, 5)) # [1, 2, 3, 4, 5] — correct
print(get_last_n(data, 6)) # [1, 2, 3, 4, 5] — silently returns all items instead of error
print(get_last_n(data, 0)) # [] — correct, but is this the right behaviour for n=0?
def get_last_n(items, n):
# Works for all typical inputs.
# Fails silently when n equals or exceeds the length of items.
return items[len(items) - n:]
data = [1, 2, 3, 4, 5]
print(get_last_n(data, 3)) # [3, 4, 5] — correct
print(get_last_n(data, 5)) # [1, 2, 3, 4, 5] — correct
print(get_last_n(data, 6)) # [1, 2, 3, 4, 5] — silently returns all items instead of error
print(get_last_n(data, 0)) # [] — correct, but is this the right behaviour for n=0?
When n exceeds the length of items, len(items) - n becomes negative. Python’s negative indexing treats that as counting from the end, so the function silently returns the entire list rather than raising an error. No exception, no warning, wrong answer.
<button data-code="fn get_last_n(items: &[T], n: usize) -> &[T] {
if n > items.len() {
panic!("n ({}) exceeds slice length ({})", n, items.len());
}
&items[items.len() – n..]
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn get_last_n<T>(items: &[T], n: usize) -> &[T] {
if n > items.len() {
panic!("n ({}) exceeds slice length ({})", n, items.len());
}
&items[items.len() - n..]
}
fn get_last_n<T>(items: &[T], n: usize) -> &[T] {
if n > items.len() {
panic!("n ({}) exceeds slice length ({})", n, items.len());
}
&items[items.len() - n..]
}
The Rust version panics explicitly when the precondition is violated rather than silently returning a wrong answer. A panic is better than silent data corruption because a panic is visible. You know immediately that the function received invalid input. Silent wrong answers can propagate through the system for minutes, hours, or days before anyone notices, and by then the original cause is buried under downstream effects.
The tests that catch boundary conditions follow the same pattern regardless of language: test with zero, test with one, test with exactly the maximum expected value, test with one over the maximum expected value. Those four cases catch the vast majority of off-by-one errors. They are also the four cases that developers most commonly skip when they are in a hurry.
The null pointer that only appears in production data
In Java and Python, null or None is a valid value for any reference type. Every function that returns an object can return null. Every variable that holds an object might hold null. The language gives you no way to express the distinction between “this variable might be null and you must check” and “this variable is guaranteed non-null and you can use it directly.” That distinction lives in the documentation, in comments, and in the programmer’s memory, all of which are unreliable.
// Java
public User findUser(String id) {
return database.query("SELECT * FROM users WHERE id = ?", id);
// might return null if user not found
// the return type User gives no indication of this
}
// somewhere else, written by someone who did not check the documentation
User user = findUser(requestId);
String email = user.getEmail(); // NullPointerException if user not found
// only happens when the user does not exist in production data
// passes all tests that use test users that do exist
// Java
public User findUser(String id) {
return database.query("SELECT * FROM users WHERE id = ?", id);
// might return null if user not found
// the return type User gives no indication of this
}
// somewhere else, written by someone who did not check the documentation
User user = findUser(requestId);
String email = user.getEmail(); // NullPointerException if user not found
// only happens when the user does not exist in production data
// passes all tests that use test users that do exist
The failure only appears when the production database does not contain the user ID that was requested. In development, tests use known user IDs that exist in the test database. The null case never triggers. The code ships and works correctly for every user that exists, and throws a NullPointerException for every user that does not.
Java’s
Optionaltype makes the possibility of absence explicit in the type signature:
<button data-code="public Optional findUser(String id) {
User user = database.query("SELECT * FROM users WHERE id = ?", id);
return Optional.ofNullable(user);
}
// now the caller is forced to handle the absent case
Optional maybeUser = findUser(requestId);
String email = maybeUser
.map(User::getEmail)
.orElseThrow(() -> new UserNotFoundException(requestId));” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public Optional<User> findUser(String id) {
User user = database.query("SELECT * FROM users WHERE id = ?", id);
return Optional.ofNullable(user);
}
// now the caller is forced to handle the absent case
Optional<User> maybeUser = findUser(requestId);
String email = maybeUser
.map(User::getEmail)
.orElseThrow(() -> new UserNotFoundException(requestId));
public Optional<User> findUser(String id) {
User user = database.query("SELECT * FROM users WHERE id = ?", id);
return Optional.ofNullable(user);
}
// now the caller is forced to handle the absent case
Optional<User> maybeUser = findUser(requestId);
String email = maybeUser
.map(User::getEmail)
.orElseThrow(() -> new UserNotFoundException(requestId));
In Python, type hints with
Optionalprovide the same signal, though they are not enforced at runtime without a type checker like mypy:
Optional[User]:
result = database.query("SELECT * FROM users WHERE id = ?", user_id)
return result
user = find_user(request_id)
if user is None:
raise UserNotFoundException(request_id)
email = user.email # safe here” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
from typing import Optional
def find_user(user_id: str) -> Optional[User]:
result = database.query("SELECT * FROM users WHERE id = ?", user_id)
return result
user = find_user(request_id)
if user is None:
raise UserNotFoundException(request_id)
email = user.email # safe here
from typing import Optional
def find_user(user_id: str) -> Optional[User]:
result = database.query("SELECT * FROM users WHERE id = ?", user_id)
return result
user = find_user(request_id)
if user is None:
raise UserNotFoundException(request_id)
email = user.email # safe here
In Rust, null does not exist. The absence of a value is represented by
Option<T>, and the type system forces you to handle theNonecase before you can access the value:
Option {
database.query("SELECT * FROM users WHERE id = ?", id)
}
let email = find_user(request_id)
.map(|user| user.email)
.ok_or(UserNotFoundError)?;” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn find_user(id: &str) -> Option<User> {
database.query("SELECT * FROM users WHERE id = ?", id)
}
let email = find_user(request_id)
.map(|user| user.email)
.ok_or(UserNotFoundError)?;
fn find_user(id: &str) -> Option<User> {
database.query("SELECT * FROM users WHERE id = ?", id)
}
let email = find_user(request_id)
.map(|user| user.email)
.ok_or(UserNotFoundError)?;
You cannot call user.email without first handling the None case. The compiler prevents it. The Java NullPointerException that only appears in production data is a class of bug that does not exist in Rust because the type system makes it impossible to write.
The tests you are probably not writing
The failure modes above share a common property: none of them are caught by tests that only check typical inputs under sequential, single-threaded conditions with clean, complete data. The tests that catch them are the ones that feel tedious to write and unnecessary until the incident happens.
Bug category Test to write Race condition Run the operation from multiple threads simultaneously, assert on the final state. If the state is wrong, you have a race. Integer overflow Test with Integer.MAX_VALUE, i32::MAX, the largest value the function will ever receive. Floating point Run the operation ten thousand times, assert the accumulated result equals the expected value exactly. Off-by-one Test with zero, one, exactly the maximum valid input, and one past the maximum. Four cases, written in five minutes. Null / absent data Test the code path where the database returns nothing, where the user does not exist, where the list is empty.
For race conditions specifically: these tests are non-deterministic by nature, which is why many developers avoid writing them. A flaky test that occasionally catches a race condition is more valuable than a deterministic test that never sees one. The flakiness is the signal.
For boundary conditions: the maximum and minimum values feel artificial when you write them. They feel obvious when they cause an incident.
The compiler catches what the compiler can see. Rust’s borrow checker eliminates an entire class of memory and concurrency bugs at compile time. Java’s type system catches some null-safety issues when you use Optional consistently. Python’s type checker catches some absence handling errors when you use Optional annotations and run mypy. None of them can see the shape of your production data, the timing windows that only open under load, or the values your users will eventually send that you did not think to test.
Correctness begins where your test suite ends. Writing the tests that check the cases you did not initially think of is harder and less satisfying than writing tests for the happy path, takes longer, and is the actual job.
If you want to go deeper on how Rust’s type system eliminates specific categories of these bugs at compile time, the field guide covers the ownership model, the borrow checker, and how they connect to the failures described here.
$7 — Zero to Rust: A Systems Programmer’s Field Guide
You can read the free sample here — Free 20-page sample


