Programming Paradigms: A must know for all Programmers

Programming Paradigms

Hackr.io.

Spread the Knowledge

Paradigm is a school of thought or model that has distinct features, frameworks, patterns, and style which help you solve a particular problem. Paradigms are used in all fields such as psychology, sociology, etymology, computer science and so on. In the field of computer science, new programming languages emerge from existing languages and add, remove and combine features in a new way. The languages may follow a particular paradigm or can be a combination of many paradigms. Did you know that there are 256 programming languages? It is evident that each of them has evolved from the other with an amalgamation of various programming paradigms.

Programming languages are tools and not all tools are good for all jobs. Some tasks are easier to solve functionally. Some are clearly suited for Objected Oriented programming. Others get simpler when you use constraint solving or pattern matching.

Programming Paradigms

Let us go on a whirlwind tour of 4 different programming paradigms – Procedural, Object-Oriented, Functional and Logical. This article will give you a better understanding of the various programming paradigms.

1. Procedural Programming

Procedural programming can also be referred to as imperative programming. It is a programming paradigm based upon the concept of procedure calls, in which statements are structured into procedures (also known as subroutines or functions). They are a list of instructions to tell the computer what to do step by step, Procedural programming languages are known as top-down languages. Most of the early programming languages are all procedural.

Examples of Fortran C and Cobol. Here is a sample code in COBOL.

IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
PROCEDURE DIVISION.
          DISPLAY ‘Hello World!’.
          STOP RUN.

Features of Procedural Code

  • Procedural Programming is excellent for general-purpose programming
  • The coded simplicity along with ease of implementation of compilers and interpreters
  • A large variety of books and online course material available on tested algorithms, making it easier to learn.
  • The source code is portable
  • The code can be reused in different parts of the program, without the need to copy it
  • The program flow can be tracked easily as it has a top-down approach.

2. Logical Programming

Logical programming is a computer programming paradigm that has its foundations in mathematical logic in which program statements express facts and rules about problems within a system. Rules are written as logical clauses with a head and a body. They also follow a declarative rather than an imperative approach. However, what does that mean?

To understand how a problem can be solved in logical programming, you need to know about the building blocks − Facts and Rules −

Let us understand the difference between Imperative and declarative programming.

Imagine you walk into your favorite coffee place and you would like to order some coffee.

The imperative approach will be:

  • Enter the coffee shop
  • Queue in the line and wait for the barista asking you for your order
  • Order
  • Yes, for takeaway, please
  • Pay
  • Present your loyalty card to collect points
  • Take your order and walk away

The declarative approach:

  • A large latte for takeaway, please

So rather than providing a step by step instruction (imperative), you tell the system what you need and let it try to come up with a solution (declarative).

Prolog follows the Logical paradigm and is probably the most famous language in the logical programming family.

Prolog has been enormously influential in the domains of theorem proving, expert systems, natural language processing and in the field of artificial intelligence (notably IBM’s Watson2) in general

Prolog, like SQL, has two main aspects, one to express the data and another to query it. The basic constructs of logical programming, terms, and statements, are inherited from logic. There are three basic statements:

  • Facts are fundamental assertions about the problem domain (e.g. “Socrates is a man”)
  • Rules are inferences about facts in the domain (e.g. “All men are mortal.”)
  • Queries are questions about that domain (e.g. “Is Socrates mortal?”)

Features of Logical Programming

  • Logical programming can be used to express knowledge in a way that does not depend on the
    implementation, making programs more flexible, compressed and understandable.
  • It enables knowledge to be separated from use, i.e. the machine architecture can be changed
    without changing programs or their underlying code.
  • It can be altered and extended in natural ways to support special forms of knowledge, such
    as meta-level of higher-order knowledge.
  • It can be used in non-computational disciplines relying on reasoning and precise means of
    expression.

3. Functional Programming

Functional programming is a programming paradigm where you have a style of building the structure and elements of computer programs. Here you treat computation as an evaluation of mathematical functions and you avoid changing-state and mutable data.

Functional programming consists only of PURE functions. So, what do you understand by Pure functions?

Pure functions are those which take an argument list as an input and whose output is a return value. Now you may feel that all functions are pure as any function takes in values and returns a value.

For example, if a function relies on the global variable or class member’s data, then it is not pure. And in such cases, the return value of that function is not entirely dependent on the list of arguments received as input and can also have side effects. So, what do you understand by the term side effect? A side effect is a change in the state of an application that is observable outside the called function other than its return value. For example: Modifying any external variable or object property such as a global variable, or a variable in the parent function scope chain.

Features of Functional Paradigm

  • Pure functions – As seen above, if the input is an array, the output will be a new array and the input array will not be modified. So in case of pure functions, the output depends only on the input.

Here’s a function in the language Scala that takes values and returns their sum.

scala> def add(a:Int,b:Int) = a + b
add: (a: Int, b: Int)Int

The add function caused no side-effects. It did not alter the input values provided, it used another pure function, the + operator, and returned the sum of the values as the result of the call. The add function is a pure function.

  • Recursion-A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, the result being outputted at the end of each iteration. Below is an example of a recursive function.
Function Count (integer N)
   if (N <= 0) return "Must be a Positive Integer";
   if (N > 9) return "Counting Completed";
else return Count (N+1);
   end function

The function Count() above uses recursion to count from any number between 1 and 9, to the number 10. For example, Count(1) would return 2,3,4,5,6,7,8,9,10. Count(7) would return 8,9,10.

You will note that recursive functions are common in computer science because they allow you to write efficient programs using a minimal amount of code. The downside is that they can cause infinite loops and other unexpected results if not written properly. For example, in the example above, the function is terminated if the number is 0 or less or greater than 9. If proper cases are not included in the function to stop the execution, the recursion will repeat forever, causing the program to crash, or worse yet, hang the entire computer system.

  • Referential transparency-An expression is said to be referentially transparent if it can be replaced with its corresponding value without changing the program’s behavior. As a result, evaluating a referentially transparent function gives the same value for fixed arguments. In functional programming, only referentially transparent functions are considered. They are a lot easier to read and understand.
int add(int a, int b)
  {
     return a + b
  }
int mult(int a, int b) 
  {
     return a * b;
  }
int x = add(2, mult(3, 4));

In this example, the mult method is referentially transparent because any call to it may be replaced with the corresponding return value. This may be observed by replacing mult(3, 4) with 12:

int x = add(2, 12)

In the same way, add(2, 12) may be replaced with the corresponding return value, 14:

int x = 14;
  • Functions are First-Class and can be Higher-Order-A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Higher-order functions are functions that take at least one first-class function as a parameter.
  • Variables are Immutable-In functional programming you cannot modify a variable after it has been initialized. You can create new variables and this helps to maintain state throughout the runtime of a program.

Strings are immutable objects.

var name = “Susie”
var uppd = name.toUpperCase()

*name will have the value – Susie
*uppd will have the value – SUSIE

Lisp is the second-oldest high-level programming language after Fortran but still in use. Lisp is a functional programming language; that is, functions are first-class objects in Lisp. However, it is not a pure-functional language such as Haskell, because operations in Lisp can have side-effects. Lisp continues to be popular in the field of artificial intelligence down to the present day.

Programming Languages that support functional programming: Haskell, JavaScript, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket.

Sample Lisp Code:

  • To evaluate the factorial of a number (n)
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (-n 1)))))
  • iterative version which uses common Lisp’s Loop Macro
(defun factorial (n)
(loop for I from 1 to n
for fac=1 then (* fac i)
finally (return fac)))
  • using recursive function
(defun –reverse (list)
(let ((return –value ‘()))
(dolist (e list) (push e return-value))
return-value))

4. Object-Oriented Programming(OO):

In this framework, all real-world entities are represented by Classes. Objects are instances of classes so each object encapsulates a state and behavior. State implies the fields, attributes of the object and behavior is what you do with the state of the object and they are the methods. Objects interact with each other by passing messages.

Features of OO:

  • Encapsulation – This is a fundamental feature of Object-Oriented Programming. Here you hide unnecessary details in classes and deliver a simple and clear interface for working. It describes the idea of bundling data and methods that work on that data within one unit. This concept is also often used to hide the internal representation, or state, of an object from the outside
  • Inheritance – Inheritance is one of the core concepts of object-oriented programming (OOP) languages. It is a mechanism where you can derive a class from another class for a hierarchy of classes that share a set of attributes and methods. It explains how the class hierarchies develop code readability and support to the reuse of functionality.
  • Data Abstraction – to Data abstraction is the reduction of a particular body of data to a simplified representation of the whole. Data abstraction is usually the first step in database design.
  • Polymorphism – Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms.

Programming languages that have implemented the OO paradigm are: Ruby, Java, C++, Python, Simula(the first OOP language)

Example of a class:

Class Account
{
 int account_number;
 int account_balance;
   public void showdata()
      {
     system.out.println(“Account Number”+account_number)
     system.outprintln(“Account Balance”+ account_balance)
      }
}

Here you have a Class named as: Account

Attributes are : account_number, account_balance
Method/Action is : showdata()

After completing a tour of programming paradigms, this article should definitely help you understand the nuances of the evolution of programming languages, and that each paradigm has contributed to the nurturing and growth of programming languages in the best interest of the programming fraternity.

People Also Read:

Related Posts

Your email address will not be published. Required fields are marked *

*