Code Correctness Rules
Common coding mistakes that cause runtime errors, unexpected behavior, or logic issues.
Python
Mutable Default Arguments
Python only instantiates default arguments once. Mutating them affects all future calls.
INCORRECT:
def append_func(default=[]):
default.append(5)CORRECT:
def append_func(default=None):
if default is None:
default = []
default.append(5)Modifying Collections While Iterating
INCORRECT:
items = [1, 2, 3, 4]
for i in items:
items.pop(0)CORRECT:
for i in list(items): # Iterate over a copy
items.pop(0)Suppressed Exceptions in Finally
Using break, continue, or return in finally suppresses exceptions.
INCORRECT:
try:
raise ValueError()
finally:
break # Suppresses the exception!CORRECT - Let the exception propagate; use finally only for cleanup:
try:
raise ValueError()
finally:
cleanup() # Cleanup runs, exception still propagatesRaising Non-Exceptions
INCORRECT:
raise "error"CORRECT:
raise Exception("error")String Concatenation in Lists
Missing commas cause implicit string concatenation.
INCORRECT:
bad = ["a" "b" "c"] # Results in ["abc"]CORRECT:
good = ["a", "b", "c"]JavaScript
Missing Template String $
INCORRECT:
return `value is {x}` // Missing $CORRECT:
return `value is ${x}`Go
Loop Pointer Export
Note: Go 1.22+ scopes loop variables per-iteration, fixing this issue. The pattern below applies to Go < 1.22.
Loop variables are shared across iterations (Go < 1.22).
INCORRECT:
for _, val := range values {
funcs = append(funcs, func() {
fmt.Println(&val) // Same pointer for all!
})
}CORRECT:
for _, val := range values {
val := val // Create new variable
funcs = append(funcs, func() {
fmt.Println(&val)
})
}Integer Overflow from Atoi
INCORRECT:
bigValue, _ := strconv.Atoi("2147483648")
value := int16(bigValue) // Overflow!CORRECT:
parsed, err := strconv.ParseInt("2147483648", 10, 32)
if err != nil {
// handles out-of-range and invalid syntax
log.Fatal(err)
}
value := int32(parsed)Java
String Comparison with ==
INCORRECT:
if (a == "hello") return 1;CORRECT:
if ("hello".equals(a)) return 1;Assignment in Condition
INCORRECT:
if (myBoolean = true) { // Assignment, not comparison!CORRECT:
if (myBoolean) {C
ato* Functions
The ato*() functions cause undefined behavior on overflow.
INCORRECT:
int i = atoi(buf);CORRECT:
char *endptr;
errno = 0;
long l = strtol(buf, &endptr, 10);
if (errno != 0 || endptr == buf || *endptr != '\0') {
// handle conversion error
}Bash
Unquoted Variable Expansion
Unquoted variables split on whitespace.
INCORRECT:
exec $fooCORRECT:
exec "$foo"Other Languages
Scala: indexOf > 0 Bug
INCORRECT:
if (list.indexOf(item) > 0) // Misses first element!CORRECT:
if (list.indexOf(item) >= 0)Elixir: Atom Exhaustion
Atoms are never garbage collected. Use String.to_existing_atom instead of String.to_atom.
OCaml: Physical vs Structural Equality
Use = not == for value comparison, <> not != for inequality.