Assertions in programming

Maaz_Bin_Asad
1 min readDec 13, 2020

--

Introduction

Managing your software is always more important than developing it. This requires following thousands of coding standards and handling hundreds of vulnerabilities and edge cases. One of the features of programming languages that helps you in your software development lifecycle is assertions. Assertions are logical functions to check whether particular requirement is met before code runs further. If that condition is not met, the program terminates and gives assertion error and doesn’t run further lines of code.

Let’s dive more into it

You wrote a code and assign a variable, let’s say x as 5. After few lines of random coding, if value of x somehow changes due to some wrong mathematical calculations, this can create problems further.

Suppose you have some potentially dangerous code starting from next line and if that code gets a value of x other than 5, your application will eventually get destroyed. To tackle this, just check if x actually contains 5 before moving on to that dangerous code.

Assertions are this much easy

Use following syntax in C++ to check above logic — assert(x==5);

If above function is correct, code goes further pretty fine, else it stops right here and throws assertion error.

Why don’t use Exception handling instead of assertions

Exception handling is not preferred for checking logical correctness of statements. For instance, while receiving data from an API in your software, you can apply exception handling to try something if data is received, except do other thing, while assertion would check if some object contains the value, that further code asks for.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Maaz_Bin_Asad
Maaz_Bin_Asad

Written by Maaz_Bin_Asad

I write blogs, poems and codes | I find myself in Machine Learning | Electronics Engineering (ZHCET)

No responses yet

Write a response