Skip to content

What is Declarative Programming?

In this lesson, you will learn declarative programming and the steps to achieve it. You will also be introduced to some real-world use cases for easy understanding.

Gopi Gorantala
Gopi Gorantala
3 min read

Table of Contents

Introduction to declarative programming

Declarative programming is a software paradigm that doesn’t change the program state at any given instance and uses the streams and some chain of methods to achieve functional programming, otherwise called the declarative style.

In functional programming, we don’t assign values as we do in imperative. Consider variables as constants declared with final , so you can understand what we are discussing here. Changing a value is not allowed.

This style of programming is analogous to SQL(Structured Query language). With streams, we move from imperative to declarative programming.

From the above understanding, we can say declarative programming embraces object immutability.

Declarative programming is how we write code by making use of Streams API

Illustrations

Declarative programming focuses on what things are. For example, in declarative programming, we do the following to run a use case.

Simple counter

Set the counter , which stores the sum of all numbers from 0 to 100.

Array of integers

Consider another example, imagine a variable data that stores the sum of all the numbers in the array divided by the length of the array.

Real-world use-cases

In the declarative approach, we use the streams and a chain of methods called intermediate and terminal operations.

1. Remove Duplicates

Removing duplicate entries from a collection is a perfect example of a declarative approach, as it deals with Streams API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Duplicates {
  public static void main(String[] args) {
    List<Integer> values = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 6, 7, 7, 8);

    List<Integer> uniqueValues =
        values // collections data
            .stream() // converting into Stream of integers
            .distinct()
            .collect(Collectors.toList()); // or you can use `.toList();`

    System.out.println("Unique list : " + uniqueValues);
  }
}

What are we doing above? let's see each of the lines we've written above in action.

List<Integer> values = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 6, 7, 7, 8);

We have a list of integer values stored in List<Integer>.

List<Integer> uniqueValues =
    values // collections data
        .stream() // converting into Stream of integers
        .distinct()
        .collect(Collectors.toList());

Line 3 is chained with .stream() to convert the collection of integer values into a stream of integers.

In line 4, we chained the stream of integers with .distinct that removes duplicate elements.

Finally, on line 5, with the help of a terminal operation .collect to collect the data into to List using Collections.toList().

Are we mutating?

No, we are not mutating the data. Each value in the stream is separate and never gets changed/updated until the stream operations are finished.

2. List Of Objects

We dealt with variables that are holding data. The following example re-iterates the same concept but for Java objects.

This is yet another simple example containing:

  1. Book POJO class.
  2. We inflate it with hard-coded data using BookRepositiryImpl class.
  3. An execution class that contains the main method, runs the application to perform the imperative approach.

Code:

public class Book {

  private final String title;
  private final String author;
  private final Integer year;
  private final Integer copiesSold;
  private final Double rating;
  private final Double costInEuros;

  public Book(
      String title,
      String author,
      Integer year,
      Integer copiesSold,
      Double rating,
      Double costInEuros) {
    this.title = title;
    this.author = author;
    this.year = year;
    this.copiesSold = copiesSold;
    this.rating = rating;
    this.costInEuros = costInEuros;
  }

  public Double getCostInEuros() {
    return costInEuros;
  }

  @Override
  public String toString() {
    return "Book{"
        + "title='"
        + title
        + '\''
        + ", author='"
        + author
        + '\''
        + ", costInEuros="
        + costInEuros
        + '}';
  }
}
import java.util.List;

public interface BookRepository {
  List<Book> getAllBooks();
}
import java.util.Arrays;
import java.util.List;

public class BookRepositoryImpl implements BookRepository {

  @Override
  public List<Book> getAllBooks() {
    return Arrays.asList(
        new Book("Don Quixote", "Miguel de Cervantes", 1605, 500, 3.9, 9.99),
        new Book("A Tale of Two Cities", "Charles Dickens", 1859, 200, 3.9, 10.0),
        new Book("The Lord of the Rings", "J.R.R. Tolkien", 2001, 150, 4.0, 12.50),
        new Book("The Little Prince", "Antoine de Saint-Exupery", 2016, 142, 4.4, 5.0),
        new Book("The Dream of the Red Chamber", "Cao Xueqin", 1791, 100, 4.2, 10.0));
  }
}
import java.util.List;
import java.util.stream.Collectors;

public class ListOfObjects {
  public static void main(String[] args) {
    BookRepositoryImpl bookRepositoryImpl = new BookRepositoryImpl();

    // Inflate fake books
    List<Book> books = bookRepositoryImpl.getAllBooks();

    List<Book> declarativeApproach =
        books // collection of books
            .stream() // stream of Book objects
            .filter(book -> book.getCostInEuros() >= 5)
            .collect(Collectors.toList());  // or you can use `.toList();`

    declarativeApproach.forEach(System.out::println);
  }
}

All the other classes other than the main class are self-explanatory.

// Inflate fake books
List<Book> books = bookRepositoryImpl.getAllBooks();

In the above execution class, we have a list of Book objects stored in List<Book>.

List<Book> declarativeApproach =
    books // collection of books
        .stream() // stream of Book objects
        .filter(book -> book.getCostInEuros() >= 5)
        .collect(Collectors.toList());

We have a collection of Book objects in line 2.

Line 3, we converted the collections of books into a stream of book objects by chaining with .stream().

Line 4, we chained the stream of books with .filter() that takes a Predicate, a condition to filter books book -> book.getCostInEuros() >= 5.

Finally, on line 5, with the help of a terminal operation .collect to collect the data into to List using Collections.toList().

The same problem as above, We are not mutating Book objects, instead each Book in the stream is separate and never gets changed/updated.

Java

Gopi Gorantala Twitter

Gopi is a highly experienced Full Stack developer with a deep understanding of Java, Microservices, and React. He worked in India & Europe for startups, the EU government, and tech giants.

Comments


Related Posts

Members Public

How To Write Lambda Expressions

This lesson introduces the basic lambda expression structure with tips to write efficient code.

Members Public

What Are Lambda Expressions?

This is an introductory lesson on lambda expressions. You will learn about the lambda operator, expression, syntaxes and more!

Members Public

Power Of Two (Exercise Problem)

This is an exercise problem for your practice. Try to come up with an approach and solve it by yourself. Good Luck!