Many of us are taught the imperative style of programming. Imperative style focusses on how to achieve the purpose of a code. This purpose is usually hidden or must be specified using comments.
For example, given a list of integers,
I want to first multiply each integer by 2, then store the integers that are > 5 in a new list. Then, I want to print that new list. Using the imperative style, we might do this:
Meanwhile, declarative style focusses on typing out what the purpose of the code is while achieving it. It is usually easier to understand what the purpose is from reading the code. Using the same example, here is the declarative style in action:
As you can see, it is easier to tell from looking at the code what we are trying to do when the declarative style is used compared to the imperative style.
Declarative programming is the recommended style going forward as it is less prone to unexpected bugs or side-effects, making writing code safer and more efficient. Java 8, released in 2014, came with major new features that support the declarative style of programming.
You can read more about it in the book “Functional Programming in Java” written by Venkat Subramaniam. Happy trying the declarative style of programming!