Assertion

Assertion

All you need to know about the assertion

Written by: saeed1907057

Sun, 17 Nov 2024

assertion

Introduction

  • This is mainly used during development and testing to verify that our certain assumption about the program is true.
  • This can help to find potential bugs early in development only.

Let us take an example:

  • Suppose, we have a function in a named findRoot(int a, int b, int c), which finds the root of the equation ax^2 + bx + c = 0 and returns the root.
  • We were told that the equation will be valid and will have only one solution. So our implementation can be as follows:
    private double findRoot(int a, int b, int c){
        int det = b*b - 4*a*c;
    
        double root = (-b + Math.sqrt(det))/(2*a);
    
        return root;
    }
    
  • The above code is fine for our scenario. But what if the equation has two roots or no root at all? It shouldnot have, but,
  • if a, b, c is read from somewhere else, then passed to the function, then there might be a possibility that the function findRoot(int,int,int) will not behave correctly.
  • It will be very hard for us to determine where the logical error is.

So, what is the solution for the previous scenario??

What if we have something during development phase, that will let us know if the equation have two or zero root? Then we can find out why the equation has two or zero root by searching through the retrieval of a, b, c. This is exactly what assertion does.

Assertion

  • State something in a strong, confident, and forceful way,
  • When we assert something, we believe that something should be true,
  • But in reality, it does not make that something always true.

How to write?

It can be written in 2 ways.

  1. assert expr;
    • This form is enough in almost all cases,
  2. assert expr : errorMessageExpression;
    • errorMessageExpression: allows writing custom error message. Can be any data type,

If expr evaluates to true, no action will be taken. Code will be executed normally. But if evaluates to false, java.lang.AsssertionError will be thrown.

Lets solve our previous problem

  • Let's see the code first

    private double findRoot(int a, int b, int c){
        int det = b*b - 4*a*c;
    
        assert det == 0;
        
        double root = (-b + Math.sqrt(det))/(2*a);
    
        return root;
    }
    
  • If we call the function with findRoot(1,2,1), it will return -1 in both cases.

  • But for findRoot(1,5,6), our previous code will return -2, but updated code will throw java.lang.AssertionError. Then we can debug the issue.

Keep in mind

  • Assertion is by default disabled. We must run our code using assertion enabled(-ea) to see assertion in action:
    java -ea OurClassName
    
  • Ex:
    java -ea .\src\Main.java
    

Another example:

Try to understand by yourself.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Bit2Byte {

    public static void main(String[] args) {
        // Today's date: 20 oct 2024
        // LocalDate dob = LocalDate.of(2001,3,21); // ok. 'User is adult'
        LocalDate dob = LocalDate.of(2021,3,21);
        int age = calculateAge(dob);

        assert age >= 8 : "User is child";
        System.out.println("User is adult");
    }

    private static int calculateAge(LocalDate localDate){
        LocalDate now = LocalDate.now();

        long age = ChronoUnit.YEARS.between(localDate,now);

        return (int)age;
    }

}

Executed using:

java -ea .\src\Bit2Byte.java

Output:

Exception in thread "main" java.lang.AssertionError: User is child
        at Bit2Byte.main(Bit2Byte.java:12)
User12024-11-02

This is a comment 1.

User12024-11-02

This is a comment 2.