Imperative vs Declarative programming models

We keep hearing these two terms very often, let's try to understand them. The imperative model is about "How", whereas the declarative model is more about "Why". Confused? Let's understand this particular statement a little better.

In the Imperative model, we describe to our computer how we want our program to be executed, we describe the control flow of the program. Some of the languages that use this model are C, C++, Java, etc.

In the Declarative model, we describe to our computer the desired state that we want at the end of the execution, and we don't have to worry about how exactly the program is going to be executed. for example in the below Ansible task, we just described that we want these packages( i.e., httpd and mariadb-server) to be installed on a particular host server, We did not tell Ansible here how to do that, now it is the duty of ansible to do that.

- name: Install the latest version of Apache and MariaDB
  package:
    name:
      - httpd
      - mariadb-server
    state: latest

Some of the tools that use this particular model are Kubernetes, Ansible, Terraform, etc.

Benefits:-

  • The advantage of the Imperative model is that it gives full control to the developers, how they want it to be executed, what they what to call their functions and variables, etc.
  • And the advantage of the Declarative model is that it simplifies the code structure of the program, and automates many of the repetitive blocks of code.