Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declarative programming and imperative programming

Tags:

paradigms

I am studying two main paradigms of programming, declarative and imperative paradigm. I am having a hard time following the ambiguous statements made on my textbook and wikipedia, such as:

declarative: - focuses on "what" the computer is to do. - is free of "side effects" - without control flow

imperative: - focuses on "how" the computer should do it. - how to do it in terms of sequence of actions

how would you differentiate the two programming paradigms? If you could expand on the statements made above, it will be very helpful.

like image 582
Midnight Blue Avatar asked Dec 08 '22 06:12

Midnight Blue


2 Answers

SQL is the classic declarative language: you say "look at this table, and give me all rows that meet these criteria" (and in real-life you use joins, select lists, whatever, but it's the same basic statement). As you noted above, this statement tells the computer what you want, not how to do it.

Internally, the database system is implemented in a language like C, and your SQL query will be translated into the following imperative steps:

while (another row to process)
    read row from disk
    for (every test)
        if (test fails)
            continue to next row
    add row to result-set

One of the key things to note here is the explicit control flow: while, for, and if. These won't appear in declarative languages.

like image 184
kdgregory Avatar answered Mar 25 '23 11:03

kdgregory


Imperative programming sequentially executes statements that may manipulate an underlying state.

Some imperative programming in java:

Customer customer = null;

// first create a customer and have the variable reference it
customer = new Customer(); 
// the state of the customer variable has changed

// set the id on whatever object is *currently* being referenced by the variable
customer.setId(1);
// the state of the Customer object has changed

customer.setFirstName("Bob");
customer.setLastName("McBob");

Note that if you do the above out of order, it would result in a null pointer exception:

Customer customer = null;
customer.setFirstName("Foo");   // the customer variable is still null at this point
customer = new Customer();   // too late!

Declarative programming doesn't have a state or order, just declarations.

Here is a simple example - this xml snippet could be considered declarative:

<NewCustomers>
  <Customer>
    <Id>1</Id>
    <FirstName>Bob</FirstName>
    <LastName>McBob</LastName>
  </Customer>
</NewCustomers>

It doesn't talk about how the customer object will get built, just declares the parts. How the above gets interpreted and executed is up to the programming environment.

like image 41
Scott A Miller Avatar answered Mar 25 '23 09:03

Scott A Miller