Sunday, November 30, 2014

Procedural Programming

The main principle behind procedural programming is to break functionality into procedures or subroutines that are carried out one after the other, to make it easier to follow and reduce the need to repeat code. As these steps are carried out, data about the program is stored globally so that all of the procedures can access the program's variables at any given time. You can also think of a procedure as a function that does not return a value, but does have side effects. Now, a side effect could include printing to the screen, writing to a file, mutating its input, updating a global variable, and so on. As a result, concurrency is harder to achieve, unlike functional programming where functions are more modular and decoupled, with less of a restriction on the order of execution.

Examples

A type of procedure in JavaScript is the alert method, which is a globally accessible function you provide with a string. Upon execution, a dialog modal is presented to the user, where the user must click a button to dismiss the window. In JavaScript, OOP is encouraged. Some languages that are inherently procedural include Fortran, COBOL, and C. Let's take a look at an example of a function and a procedure, using C.

// function
int square( int n ) {
   return n * n;
}

// procedure
void display( int n ) {
   printf( "The value is %d", n );
}

Note how the function returns a value and the procedure doesn't. The function in this case can be considered a Pure Function because it doesn't rely on or modify anything outside of its scope and it doesn't cause any side effects. Here's another example in PHP, where the subtract function returns a value, but the subtract procedure mutates the input.

// function
<?php
function subtract($a, $b) {
    return $a - $b;
}

// procedure
<?php
function subtract(&$a, $b) {
    $a = $a - $b;
}

Summary

Advantages

  • Requires less overhead than OOP
  • Simpler paradigm over OOP (no need to learn about polymorphism, inheritance, etc.)
  • Strict control over the order of execution

Disadvantages

  • Dependency hell due to the mutation of global properties and shared states
  • Difficult to debug
  • Strict control over the order of execution actually becomes a con when attempting to achieve concurrency
  • Shared state makes it harder to achieve concurrency

That's it for this article. Make sure to check out this article on object oriented programming if you're curious about other programming paradigms.

No comments:

Post a Comment