the Chromium logo

The Chromium Projects

Invariants and CHECKKs in C++

Defensive vs offensive coding

Defensive programming is the practice of writing software to enable continuous operation after and while experiencing unplanned issues. However, while defensive coding will result in code that is more resilient to crashes, it can leave the system running in an undefined state. Devices that are in an undefined state are broken and need to be reset. By using defensive programming, you are continuing the device's state to handle an undefined situation, which leaves the system vulnerable and masks the error.

Offensive programming, although seemingly opposite word choice, actually expands upon defensive programming and takes it one step further: instead of gracefully handling a failure point, offensive programming asserts that invariants always hold, and reveals to developers any information that will be helpful to debug.

See "Defensive Programming: Friend or Foe" for more information.

CHECK(), DCHECK(), NOTREACHED_NORETURN() and NOTIMPLEMENTED()

Assertions are an important tool of offensive programming to enforce assumptions and code paths that we expect to be a certain way. See this README for more information on this topic. Below are commonly used assertions:

See here for a shorthand reference.