# 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](https://lessloc.org/patterns/index.md). What lessloc does: [`defensive`](https://lessloc.org/guide/reference.md#tier-2) 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`](https://lessloc.org/guide/reference.md#tier-2) 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 [ce.py]
def make():
    user = User("ada")
    if user is None:
        raise ValueError("no user")
    return user
```

Written well:

```python [ce.py]
def make(name):
    if not name:
        raise ValueError("name is required")
    return User(name)
```

Caught as `defensive`:

```ts [cf.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 [cf.ts]
export function label(id: string) {
  if (typeof id !== "string") throw new Error("id must be a string");
  return id;
}
```

## Related patterns

The other patterns in [Errors and checks hidden](https://lessloc.org/patterns/index.md#errors-and-checks-hidden):

- [Swallowed errors](https://lessloc.org/patterns/swallowed-error.md): lessloc catches it as `swallowed-error`.
- [Silenced checks](https://lessloc.org/patterns/silenced-checks.md): lessloc catches it as `suppression`.
- [Removing validation or error handling to shrink code](https://lessloc.org/patterns/removed-safeguard.md): lessloc catches it as `removed-safeguard`.
