Declarative, Functional & Imperative Programming: Must Know Paradigms For Software Developers
Declarative, functional, and imperative are different programming paradigms that describe how to write computer programs. I would try to explain them in simple terms with some examples.
So, grab your coffee and enjoy reading !
Declarative Programming
Declarative programming focuses on what needs to be done, rather than how to do it. It is concerned with expressing the logic, without specifying the control flow. The following is an example of declarative style programming in java:
Stream<Integer> numbers = Arrays.stream(new Integer[] {1, 2, 3, 4});
int sum = numbers.reduce(0, Integer::sum);
System.out.println(sum); // outputs 10
The way we have calculated sum here is done by following declarative programming. To explain the code, in this code numbers.reduce(0, Integer::sum) takes 0 as seed value, calls Integer::sum ( method reference syntax used here i.e. Class::methodName which is same as Class.methodName() ) to take 2 numbers each time and return the value to sum variable.
All of these are abstract, as in declarative programming, we mention only what to do, not how to do.
When is Declarative Programming generally used? SQL queries, HTML/CSS, Regular expressions
Real Life Example of Declarative Style Programming In Software Development
SQL: In SQL, developers use declarative statements to describe the desired results. For example, to retrieve all the records from a database table where the value of the “age” column is greater than 18, we would use the following SQL statement:
SELECT * FROM my_table WHERE age > 18;
Java: When a class is annotated with @Autowired, Spring Framework automatically injects the required dependencies into the class at runtime. This eliminates the need for manual dependency injection code and allows developers to focus on the high-level design of their application
JavaScript: One example of declarative programming in JavaScript is the use of React, a popular front-end library for building user interfaces.
import React from 'react';
function ExampleComponent(props) {
return (
<div className="example">
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
);
}
In this example, the ExampleComponent
function defines a UI component that renders a <div>
element with a title and description. The structure and behavior of the component are defined declaratively using the JSX syntax. The props
object is used to pass data to the component, making it easy to reuse the component with different data.
Functional programming
Function is the first class citizen here
Functional programming is a declarative paradigm in which the basic building blocks are functions that map input to output, without having any side effects. Example: Haskell, LISP, and so on.
Following is an example of functional programming in java:
Function<Integer, Integer> factorial = n -> n == 0 ? 1 : n * factorial.apply(n - 1);
System.out.println(factorial.apply(5)); // outputs 120
Here factorial
is a function that maps input to output where n is the input and n == 0 ? 1 : n * factorial.apply(n — 1) shapes the output.
the factorial
function doesn't have any side effects because it only takes an input and returns an output, without modifying any external state or performing any I/O operations.
Bonus: The syntax of Function<Integer, Integer> means the input type is Integer and output type is Integer and this is a functional interface syntax in java which has only one method in the interface namely apply()
When is Functional Programming generally used? System programming, Game development, Operating system development.
Real Life Example of Functional Style Programming In Software Development
SQL: SQL is a declarative programming language used for managing relational databases. It supports functional programming through its use of aggregate functions, which take a set of values and produce a single result. For example, the following SQL query calculates the total sales for each product category in a sales table in which SUM
function is an example of a higher-order function that takes a set of values and produces a single result
SELECT category, SUM(sales) AS total_sales
FROM sales_table
GROUP BY category;
Java: Java is an object-oriented programming language, but it also supports functional programming through its support for lambda expressions and functional interfaces. Lambda expressions are anonymous functions that can be passed as arguments to other functions, and functional interfaces are interfaces that specify a single abstract method. Here’s an example of a Java method that uses a lambda expression to filter a list of strings based on a predicate.
public List<String> filterList(List<String> list, Predicate<String> predicate) {
return list.stream().filter(predicate).collect(Collectors.toList());
}
// Usage:
List<String> myList = Arrays.asList("foo", "bar", "baz");
List<String> filteredList = filterList(myList, s -> s.startsWith("b"));
Here, the filterList
method uses the stream
method to convert the list to a stream, and then uses the filter
method to apply the predicate to each element. Finally, the collect
method is used to convert the filtered stream back to a list.
Javascript: JavaScript includes several built-in higher-order functions, such as map
, filter
, and reduce
, that are commonly used in functional programming. Here's an example of a JavaScript function that uses the reduce
function to calculate the sum of all the even numbers in an array:
function sumEvenNumbers(arr) {
return arr.filter(x => x % 2 === 0).reduce((acc, curr) => acc + curr, 0);
}
// Usage:
const myArray = [1, 2, 3, 4, 5, 6];
const sum = sumEvenNumbers(myArray);
Here, the filter
method is used to select only the even numbers in the array, and the reduce
method is used to add them up. The reduce
method takes two arguments: an accumulator and the current value. The accumulator is initialized to 0
, and the current value is added to it for each element in the filtered array.
Imperative Programming
Imperative programming is a programming paradigm that focuses on describing how a program operates. It specifies the steps the computer must take to solve a problem, usually using statements that change a program state. Example: C, C++, and Java.
Following is an example of imperative programming in java:
int sum = 0;
for (int i = 0; i <= 10; i++) {
sum += i;
}
System.out.println(sum); // outputs 55
As you can see, the program focuses on the steps to take to produces the desired outputs.
When is Imperative Programming Generally Used? System programming, Game development, Operating system development.
Real Life Example of Imperative Style Programming In Software Development
SQL: Following is an example of imperative style programming in SQL
UPDATE employees
SET salary = salary * 1.1
WHERE department = 'engineering';
This SQL statement is imperative because it specifies how to update the data in the “employees” table.
Javascript: Imperative programming in javascript
function changeBackgroundColor(color) {
var body = document.getElementById("body");
body.style.backgroundColor = color;
}
This JavaScript code is imperative because it specifies how to change the background color of the web page using the DOM.
That’s a wrap! Follow for more. Let me know any suggestions in comment.