Declarative Programming
Learn about declarative programming.
We'll cover the following...
What is declarative programming?
To understand what declarative programming is, we can compare it to something we know, and that is imperative programming. In imperative programming, we focus on describing how something will be done. In declarative programming, on the other hand, the focus is on what we want to achieve.
To understand this, we’ll look at some real-world examples. If you go to a restaurant, you can either be an imperative or declarative guest.
The imperative guest would make an order like this:
“I would like the cod, please. First, bake it in the oven for 10–12 minutes. Please check it regularly so it won’t overcook. While the cod is in the oven, please boil the potatoes. To prepare the cream sauce, first, melt some butter in a medium-sized pan over medium heat. Slowly add corn starch and stir for about a minute. While constantly whisking, slowly add whipping cream and milk. Finally, add some parmesan cheese. Let the sauce reduce on low heat while whisking occasionally.”
On the other hand, if you were a declarative restaurant guest, you would say something like this:
“I would like the cod, please.”
The first guest answers the question of how, while the second one focuses on what.
An excellent example of something declarative in computer science is SQL. It is an abbreviation of Structured Query Language and is used to store and retrieve data from databases. If we want to get the first and last name of all the customers stored in the customer’s table, we could write the following:
SELECT firstName, lastName FROM customers;
This is declarative because we say what we want—the first and last names of the customers—but we say nothing about how the data will be retrieved. Somewhere in the underlying database system, some parts must know how this will be done, but if we’re using SQL, we don’t need to know or understand it.
Python is a programming language where we can write both imperative and declarative ...