Functional Programming has been thriving in recent times. It is actually a way of life. The main challenge here is to unlearn the OOPS way of life and then learn the Functional Programming way. Once you learn it, it makes life so easy, it’s more concise, predictable, and less complex. Testing the code becomes seamless.

There are two types of programming — Imperative and Declarative, Functional programming is a declarative way of programming. Functional programming is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. The application state flows through pure functions.

So let’s look into what are the things we need to learn to adapt to the functional way of life.

Imperative vs Declarative Approach

We’ll take an example and see how we can code for it in both approaches

public class App {
		public static void main(String[] args) {
			List<Person> people = Arrays.asList(new Person("Vinesh", Gender.MALE), 
							   new Person("Neha", Gender.FEMALE),
					new Person("Sameer", Gender.MALE), new Person("Rakshith", Gender.MALE),
					new Person("Swaroop", Gender.MALE), new Person("Saurabha", Gender.FEMALE),
					new Person("Naina", Gender.FEMALE));
	    }

		static class Person {
			private final String name;
			private final Gender gender;

			public Person(String name, Gender gender) {
				this.name = name;
				this.gender = gender;
			}
			@Override
			public String toString() {
				return "Person [name=" + name + ", gender=" + gender + "]";
			}
		}
		enum Gender { MALE, FEMALE }
	}

Let’s say we have the above code and we want to filter all females from the list, let’s first print all females using both imperative & declarative method.

// Imperative approach
	for (Person person : people) {
		if (Gender.FEMALE.equals(person.gender)) {
			System.out.println(female);
		}
	}

// Declarative approach
people.stream().filter(person -> Gender.FEMALE.equals(person.gender))
.forEach(System.out::println);


The imperative code is too big for a simple task whereas the declarative method achieves it with just a single line.

#object-oriented #coding #java #functional-programming #programming

Functional Programming — It Is A Way Of Life
1.40 GEEK