Programming paradigms : Part 1

Programming paradigm is as style or way of programming.

If you are studying a programming language, in its feature list the first place is always reserved for programming paradigm it follows.

If a programming language L happens to make a particular programming paradigm P easy to express, then we can say that “L is a P language”. For example, C is a procedural language.

Note that Paradigms are not meant to be mutually exclusive; a single program can feature more than one paradigms.

There are lots of programming paradigms; we will look at some major paradigms you must know. As post is bulky, I have divided it into 2 parts.

To visit Programming Paradigm : Part 2, click here.

 

Programming Paradigm

Explanation

Imperative

Programming with sequence of statements to determine how to reach certain goal.

Procedural

Imperative programming with procedure (function) calls.

Declarative

Programming which specifies what result you want, not how to get it.

Structured

Goto free programming. Using nested loop, conditionals, procedures (functions) to control program flow.

Functional

Programming which treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Event Driven

Flow of program is determined by events.

Logic

Programming by specifying set of facts and rules. An engine infers answers to questions.

Constraint

Programming by setting constraints. Engine filters value by constraints.

Aspect oriented

Addressing problem of cross cutting concern.

Object oriented programming

Programming by defining objects that communicate with each other to derive results.


 

Imperative Programming

Let’s take example, mom ask child, who is just 3 year old, to turn on the light.

Her instructions would be as follows:

1.     Get down from bed

2.     Bring a chair near switch board

3.     Stand on it

4.     Look for the switch having symbol of bulb

5.     Press the switch

Here, you can see that mom is instructing child how to do task. This is what imperative programming is, where in program we specify how computer should do a task.

Definition

An imperative language uses a sequence of statements to determine how to reach a certain goal. These statements are said to change the state of the program as each one is executed in turn.

Example:

To add series of numbers one by one. Consider, series has 3 numbers.

int a = 5;

int b = 6;

int c = 7;

int d = a + b;

int e = d + c

Explanation:  In this program computer has been instructed as, create three variables with values as specified. Then add first 2 numbers. To the result add next number.

 

This is imperative programming.

 

Programs written this way are often compiled to binary executable. Binary executables runs efficiently as all CPU instructions are themselves imperative statements.

To make code simple and human readable, we can group statements; the group is called as code block.

 

Procedural Programming

Consider a procedure of college admission. The steps you need to do are as follows:

1.     Go to ‘forms section’ and collect forms.

a.     Pay for form

b.     Receive form from representative sitting there

2.     Fill the form by writing

a.     Your name

b.     Date of birth

c.      Address

d.     Many more things

3.     Go to ‘document verification section’

a.     Show original documents

b.     Show photocopies and get them approved from representative

c.      Get verified the form filled in earlier step.

4.     Pay fees at ‘accounts section’

5.     Submit the form ,documents and payment slip to ‘documents submission section’

 

Here you may ask that, what difference between imperative programming and procedural programming is? The answer is, if you look carefully, the procedure of doing task is divided into subsections and how to do task at that subsection is written inside it, as points a,b,c etc.

Definition

Procedural programming is a programming style which relies on well-organized functions or procedures in programs architecture by specifying all steps that computer should take to get desired output.

Example:

To write calculator program

int main(){

 

    int num1 = acceptNumber();

    int num2 = acceptNumber();

 

    int addition = add(num1 , num2);

 

    int subtraction = sub(num1 , num2);

    return 0;

}

 

int acceptNumber (){

    scanf(" %d ", &a);

}

int add( int num1, int num2){

    return num1 + num2;

}

 

int sub( int num1, int num2){

    return num1 - num2;

}

 

Explanation: Here computer has been told about how to accept number from user, how to add 2 numbers and how to subtract 2 numbers in separate functions. And sequence of calling these functions is specified in main() function.

 

Along with how to of imperative programming, program is well organized in multiple functions. This is procedural programming.



 

Declarative Programming

Suppose you want your house to get painted. So you call carpenter and describe him what are your expectations and conditions. You left up to him how to complete task.

Same is with declarative programming where you only describe what you want to do, not necessarily how to get it done. The best example is SQL where you just specify query and have no concern how engine executes query and brings results.

Definition

A style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.

Example:

You want to fetch id and name of employee whose salary is 50000 from database.

Select id , name from employee_data where salary = 50000;

Explanation: In this query, we specified on what condition data should be filtered. In contrast to imperative or procedural programming, we are least bother of how to execute query and fetch data. We rely on database engine, which will decide flow executing query.

 

Example:

 

We have collection of numbers. We want to separate list of odd numbers. Writing code in c#. (Don’t consider syntax for now. Just look at logic.)

List<int> collection = new List<int> { 1, 2, 3, 4, 5 };

 

// Imperative programming

 

List<int> results = new List<int>();
foreach(var num in collection)
{
    if (num % 2 != 0)
          results.Add(num);
}

 

// Declarative programming

 

var results = collection.Where( num => num % 2 != 0);

 

Explanation: Variable collection is list of numbers.

 

With imperative programming, we tell the compiler what we want to happen, step by step.

 

With declarative programming, on the other hand, we write code that describes what we want, but not necessarily how to get it (declare your desired results, but not the step-by-step)

 

Supporting languages: Prolog, Database query languages such as SQL.






Structured Programming

Consider your parents are planning to go out of city for few days. Your mom is aware that you know how to boil milk. Instead of calling you every day and ask to boil milk she will set a repetitive reminder in mobile phone. This reminder will be triggered repeatedly and will call procedure of boiling milk.

Don’t you think this is more structured way of doing task instead of calling you every day? Similar is with structured programming. Consider repetitive reminder as loop and procedure of boiling milk as function.

 

So, in simple words, you can say in structured programming flow is defined by nested loops, conditionals, functions.

Definition

Structured programming is a kind of imperative programming where control flow is defined by nested loops, conditionals, and subroutines, rather than via gotos.

Example:

Create a list of odd numbers from collection of numbers using C#. #. (Don’t consider syntax for now. Just look at logic.)

List<int> collection = new List<int> { 1, 2, 3, 4, 5 };

 
List<int> results = new List<int>();
foreach(var num in collection)
{
    if (num % 2 != 0)
          results.Add(num);
}

 

Explanation: We used for loop to iterate through list. Applied filter using if(condition) and then used Add(n) to add filtered number to list.

 

This is structural programming.

 

Supporting Languages: PL/I, ALGOL, COBOL, Verilog etc.

 

Functional Programming

Consider there is a variable declared in function. We can change value assigned to variable, so it is called as mutable.

Do you know : Mutable vs Immutable Objects

Mutable object: Objects whose value can be changed is called as mutable object.

Eg. Integer a = 10;

      a = 20;

Value of a is 20.

     

Immutable object:  Objects whose value cannot be changed without re-assigning new value is called immutable object.

Eg. String is called as immutable object. How lets see.

Eg. String str = "Hello";

str + "world";

 

Value of str is "Hello" as its value cannot be changed.

 

To change immutable objects value we need to re-assign value to it.

 

str = str + "world";

 

Now, value of string is "Helloworld"

 

 

During computation if we changed value of variable, it is called as change in state of code. The code is said to be code with side effects.

Functional programming treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Avoid changing -state means no input variable’s value changed inside function. Code which doesn’t change global state of code is also called as code without side effects.

Definition

Functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

You might ask why word mathematical functions is used here? Before explaining, lets see definition of mathematical functions.

Mathematical functions: In mathematics, a function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output.

In case of functional programming, for argument x, f(x) will always produce same result. Thus it’s most suitable word to explain functional programming.

 




Features of functional programming:

·        High order functions

o   Higher-order functions (HOFs) are functions that take other functions as their arguments.

o   A basic example of a HOF is map in Haskell (a function programming language), which takes a function and a list as its arguments, applies the function to all elements of the list, and returns the list of its results.

o   For instance, we can write a function that subtracts 2 from all elements of a list without using loops or recursion:

subtractTwoFromList l = map (\x -> x - 2) l

 

·        Immutable data

Instead of altering existing values in variable, a copy of variable is created and operations are performed on it.

 

·        Referential transparency

Referential transparency is the ability to freely replace an expression with its value and not change the behavior of the program.  Its main benefit is the compiler being able to do something with an expression.  If an expression's output is unpredictable, a compiler can't optimize the code at all, and the program must wait to see what the expression evaluates to at runtime.

 

For example,

 

int addOne(int x){

return x+1;

}

 

With this function, compiler can easily determine that given an input of 5 , the expression addOne(5) will evaluate to 6. It can just replace that with 6 and make it faster at runtime.

 

However,

 

//global G

int G = 20;

 

int addG(int x){

//G can be modified externally returning different values

 

return x + G;

}

 

In this example, let’s say G can be modified externally, by something outside of compiler’s control. It can't replace addG(5) with anything. The expression can only be evaluated at runtime because the potential of modification makes it referentially "opaque".

 

·        Lazy evaluation

Since functional programming supports referential integrity, the computations can be performed at any time and still yield same result. Such computations can be postponed and be done when needed by code. This is called as lazy evaluation.

 

·        Recursion

Recursion is accepted by functional programming languages as their need and because of performance benefits as well. As we studied earlier, pure functional language should have feature called no side effect. Which means you can’t have loop counters (because a loop counter would constitute mutable state, and modifying such state would be a side effect). Recursion, however, is a natural match with pure functional programming – no state is needed to recurse. Not having side effects also means that recursion can be implemented more efficiently, and the compiler can optimize it more aggressively.

 

Do you know : Functional programming considers function as first class citizen

The first class function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to variable.

 

What is difference between first class function and high order function?

 

First class function can be passed as an argument to other function and can be assigned as value to variable. Whereas, high order function take one or more functions as argument and can return function. The argument and return function of high order function can be first class function.

 

Topics covered in part 2:

·        Event driven programming

·        Logic  and constraint programming

·        Aspect oriented programming

·        Object oriented programming

To visit Programming Paradigm: Part 2 click here.

No comments:

Post a Comment

Operators in Java

Operator is a symbol which is used to perform operation on data. Eg. +,-,/,* etc. Do you know : Operator and operan...

Popular