Skip to content

Checks, fallbacks and catches for cases that cannot happen ​

Errors and checks hidden: one of the ways AI coding agents bloat software, from lessloc's pattern catalog. What lessloc does: defensive catches a null check of a value just created, a type re-checked inside private code and ?. on a fresh object.

What makes checks, fallbacks and catches for cases that cannot happen a bad practice? ​

The standards that call it a bad practice: Meyer, "Applying Design by Contract" (IEEE Computer, 1992): "never in both… avoid redundant tests"; Ousterhout: Define Errors Out of Existence; Anthropic's prompting guide: "Don't add error handling, fallbacks, or validation for scenarios that can't happen".

What does lessloc do about checks, fallbacks and catches for cases that cannot happen? ​

defensive catches a null check of a value just created, a type re-checked inside private code and ?. on a fresh object.

  • defensive (tier 2): A check for a case that cannot happen, such as testing a value just created for emptiness.

Examples ​

Caught as defensive:

python
def make():
    user = User("ada")
    if user is None:
        raise ValueError("no user")
    return user

Written well:

python
def make(name):
    if not name:
        raise ValueError("name is required")
    return User(name)

Caught as defensive:

ts
function label(id: string) {
  if (typeof id !== "string") throw new Error("id");
  const parts = { id };
  return parts?.id;
}
export const show = (id: string) => label(id);

Written well:

ts
export function label(id: string) {
  if (typeof id !== "string") throw new Error("id must be a string");
  return id;
}

The other patterns in Errors and checks hidden:

Released under the Apache-2.0 license. · llms.txt