Using assertions in the code

Reading time2 min

Important takeaways

Assertions are made to validate and enforce expected conditions in the code during runtime.

  • Assertions validate assumptions in the code, preventing bugs and logical errors.
  • Failed assertions provide immediate feedback, helping developers quickly identify and fix issues.
  • Consistent use of assertions enforces constraints, leading to more robust and reliable software.

Introduction

Assertions are a crucial tool in software development used to validate assumptions made in the code. They check whether specific conditions hold true during execution, helping to catch bugs and logical errors early. When an assertion fails, it provides immediate feedback, aiding in quick debugging. By enforcing constraints and expected behaviors, assertions contribute to creating more reliable and maintainable code.

Assertions

The assertion mechanism is used to check conditions during code execution. Most of the time, it does not require any additional dependency.

In Python (as in Java), an assertion is added using the reserved word assert, followed by the condition to be checked, and an optional message

def euclidean_division(a:int, b: int) -> int:
    assert b !=0, "Division by zero"
    return a // b
public int euclideanDivision(int a, int b){ 
    assert b !=0 : "Division by zero";
    return a / b;
}

Assertions can function as a form of documentation: they can describe the state the code expects to find before it runs. Assertions can be used to document code by indicating code invariants and thus be seen as a form of documentation. However, assertions are only used in the development phase and are rendered silent in production.

It is advisable to distinguish the code test from the code itself when checking the correctness and the consistency of a code with the specifications to which it must respond. It is common practice to include some elements of program documentation within the code itself.