DEV Community

Clean Code Studio
Clean Code Studio

Posted on • Edited on

Function Pre-conditions & Post-conditions (What are they?)

Note: Code examples NOT written in JS.

Components of a function

  • name: used identify function
  • args: containing objects to operate on
  • body: Transform args and execute the logic
  • return: Specifies the result from the given function
Function: {     
   name: 'addOne',     
   args:  numeric,     
   body: sum = numeric + 1,     
   return: sum  
}
Enter fullscreen mode Exit fullscreen mode

Pre-condition of a function

A pre-condition defines a condition that must be true before a function can be run.

For example, we could conditionally confirm that numeric is an integer.

function addOne (numeric) {
   if (typeof numeric !== 'integer') {
     throw new Error('parameter must be an integer')
   }

   let sum = numeric + 1

   return sum
}
Enter fullscreen mode Exit fullscreen mode

We have added a pre-condition to our function. The condition states that numeric arg must be of type integer.

A concise way to add a pre-condition is to use type checking on the function input. (given your language allows it typescript, Java, C++, etc...).

function addOne(integer numeric) {   
   let sum = numeric + 1
      
   return sum
}
Enter fullscreen mode Exit fullscreen mode

Type checking numeric pre-conditionally enforces that numeric must of type integer. This is an example of a pre-condition.

A post-condition defines a condition that must be met in order to return the result from said function.

function addOne(numeric) {    
    let sum = numeric + 1     

    if (typeof sum !== 'integer') {       
       throw new Error(`addOne must return integer type`)
    }
    return sum
}
Enter fullscreen mode Exit fullscreen mode

An example of a post-condition is to type check the returned result of the function. (Given the language you're using allows type checking return values - typescript, PHP, Java, etc...)

function addOne (numeric) : integer {    
   return numeric + 1
} 
Enter fullscreen mode Exit fullscreen mode

And adding both a pre-condition and post-condition.

function addOne (integer numeric) : integer {
   return numeric + 1
}
Enter fullscreen mode Exit fullscreen mode

Pre-conditions and post-conditions, especially via type checking are extremely powerful concepts to understand.

They narrow down the number of side effects incurred throughout an application, are used to enforce powerful design principles like the infamous L from SOLID: Liskov's Substitution Principle, and when used within both Functional and Object Oriented Programming empower developers to better scale as well as re-use their code with confidence.


Clean Code Studio
Liskov's Substitution Principle
Functional Programming
Functional Programming - First Class Functions
Interfaces in Object Oriented Programming
Cryptocurrency
Cardano
Cardano Unspent Transaction Output

Top comments (0)