Functional Programming For Java Developers

Posted By : Harshit Verma | 30-May-2019

What is functional programming?


Functional programming is the programming style in which computations are codified as the functional programming functions. These are the mathematical function-like constructs (e.g., lambda functions) that are evaluated in the expression contexts.

 

Functional programming languages are declarative, meaning that a computation's logic is expressed without describing its control flow. In declarative programming, there are no statements. Instead, programmers use expressions to tell the computer what needs to be done, but not how to accomplish a task. If you are familiar with the SQL or regular expressions, then you have some experience with declarative style; both use expressions to describe what needs to be done, rather than the using statements to describe how to do it.

 

A computation in functional programming is described by the functions that are evaluated in expression contexts. These functions are not the same as functions used in imperative programmings, such as a Java method that returns the value. Instead, a functional programming function is like a mathematical function, which produces the output that typically depends only on arguments. Each time the functional programming function is called with the same arguments, the same result is achieved. Functions in functional programming are said to the exhibit referential transparency. This means you could replace the function call with its resulting value without changing computation's meaning.

 

Functional programming favours the immutability, which means the state cannot change. This is typically not case in imperative programming, where an imperative function might be associated with the state (such as the Java instance variable). Calling this function at different times with the same arguments might result in the different return values because in this case state is the mutable, meaning it changes.

 


Object-oriented versus functional programming

I have created a Java application that contrasts the imperative, object-oriented and declarative, functional programming approaches to the writing code. The code below and then I will point out differences between the two examples.


Listing 1. Employees.java

 

import java.util.ArrayList;

import java.util.List;

public class Employees

{

   static class Employee

   {

      private String name;

      private int age;

      Employee(String name, int age)

      {

         this.name = name;

         this.age = age;

      }

      int getAge()

      {

         return age;

      }

      @Override

      public String toString()

      {

         return name + ": " + age;

      }

   }

   public static void main(String[] args)

   {

      List<Employee> employees = new ArrayList<>();

      employees.add(new Employee("John Doe", 63));

      employees.add(new Employee("Sally Smith", 29));

      employees.add(new Employee("Bob Jone", 36));

      employees.add(new Employee("Margaret Foster", 53));

      printEmployee1(employees, 50);

      System.out.println();

      printEmployee2(employees, 50);

   }

   public static void printEmployee1(List<Employee> employees, int age)

   {

      for (Employee emp: employees)

         if (emp.getAge() < age)

            System.out.println(emp);

   }

   public static void printEmployee2(List<Employee> employees, int age)

   {

      employees.stream()

               .filter(emp -> emp.age < age)

               .forEach(emp -> System.out.println(emp));

   }

}

Listing 1 reveals the Employees application that creates the few Employee objects, then prints a list of all the employees who are younger than the 50. This code demonstrates both the object-oriented and functional programming styles.

 

The printEmployee1() method reveals an imperative, statement-oriented approach. As specified, method iterates over the list of employees, compare each employee's age against the argument value, and (if the age is less than the argument), prints employee's details.

 

The printEmployee2() method reveals declarative, expression-oriented approach, in this case, implemented with Streams API. Instead of imperatively specifying how to print employees, expression specifies the desired outcome and leaves details of how to do it to Java. Think of filter() as functional equivalent of an if statement, and forEach() as functionally equivalent to statement.

 


Functional programming examples


Listing 2 presents source code to RunScript, a Java application thatuses

the Java's Scripting API to facilitate running JavaScript code. RunScript will be the base program for all of the forthcoming examples.

 

Listing 2. RunScript.java
 

import java.io.FileReader;

import java.io.IOException;

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

import static java.lang.System.*;

public class RunScript

{

   public static void main(String[] args)

   {

      if (args.length != 1)

      {

         err.println("usage: java RunScript script");

         return;

      }

      ScriptEngineManager manager = 

         new ScriptEngineManager();

      ScriptEngine engine = 

         manager.getEngineByName("nashorn");

      try

      {

         engine.eval(new FileReader(args[0]));

      }

      catch (ScriptException se)

      {

         err.println(se.getMessage());

      }

      catch (IOException ioe)

      {

         err.println(ioe.getMessage());

      }      

   }

}

 

The main() method in this example first verifies that the single command-line argument has been specified. Otherwise, it displays usage information and terminates the application.

 

Assuming the presence of this argument, main() instantiates  javax.script.ScriptEngineManager class. ScriptEngineManager is  entry-point into Java's Scripting API.

 

Next,ScriptEngineManager object's ScriptEngine getEngineByName(String shortName) method is called to obtain the script engine corresponding to desired shortName value. Java 10 supports Nashorn script engine, which is obtained by passing "nashorn" to getEngineByName(). The returned object's class implements javax.script.ScriptEngine interface.

 

ScriptEngine declares several eval() methods for evaluating script. main() invokes Object eval(Reader reader) method to read the script from its java.io.FileReader object argument and (assuming that java.io.IOException isn't thrown) then evaluate the script. This method returns any script return value, which ignores. Also, this method throws the javax.script.ScriptException when the error occurs in script.

 

About Author

Author Image
Harshit Verma

Harshit is a bright Web Developer with expertise in Java and Spring framework and ORM tools Hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..