Functional Programming in Java

Post on 15-Feb-2017

183 views 1 download

Transcript of Functional Programming in Java

Functional Programming in Java

Narendran, S S

THERE IS A CHANGE IN “THE CLIMATE” TO CHANGE OUR WAYS

“LAMBDAS IN JAVA 8 IS NOT FOR WHAT THEY CAN DO, IT IS ABOUT HOW WE WRITE PROGRAM”

IT ENABLES FUNCTIONAL PROGRAMMING, IT ADDS A NEW NUCLEOTIDES IN THE DNA OF JAVA.

Structural Reflective

Object Oriented

Functional &

Declarative

Imperative

Concurrent Generic

My FP Inspirations!!!

Douglas Crockford Mario Fusco

Brian Goetz Venkat Subramaniam

“JavaScript: The Good Parts” Book Author

“Java 8 in Action” Book Author

Java Specification Lead

“Java Lambdas is one of the specificaiton”

“Functional Programming in Java” Book Author

We need to move Out of OOPBox

Are We Ready to Jump out of OOP Box?

STAGE 1

Understanding Three Basic Concepts required for Functional Programming.

It may be already

Familiar to you.At the end,

You will be on Trampoline… Ready

to Jump…

I Understand that it is difficult to Jump to an another Paradigm all at

once We shall ground our self with the required Concepts, 1. Behavioural Parameterization2. Lazy Evaluation & Lazy Initialization3. Lambdas

Behavioural Parameterization

• Context: Usually requirements keeps changing, it leads to a lot of code changes and maintenance.

• Behavioural Parameterization is all about Extracting this “Changing Behaviour” out of the Context.

• Requirement: Filter green Apples from a bunch of Apples.

• Change: Add a Support to filter apples by Weight

• Change: More Changes

The Code Bloats

Do We see a pattern!!! Question: Based on which characters the

changes happens?

Refinement 1: Creating a Strategy

After Refinement 1, We send a “Behaviour” as “Parameter”.

This is called “Behavioural Parameterization”

Hurrah!!!

Refinement 2: Proactive support for Oranges and More… Generic Programming with Generics

Hurrah!!!

We did even great!!!We have reached our best with Java 7

Next: Lazy Evaluation & Lazy Initialization.

Next?

Lazy Evaluation

In the above Example, we passed the “behaviour” not the “value” after executing the behaviour.

Until if condition is reached this behaviour is not evaluated. This is called “Lazy Evaluation”

Lazy Initialization

“Simple Values” like colour Blue & Green enclosed as “Behaviours”

Lazy Initialization

The Colour Supplier behaviour which carries the value never got evaluated until it is called to set the colour for the Wall inside get colour.

Actually the “state” of the Wall Colour was not initialized despite the wall construction with “state” until required.

Similar to change

in Behaviours,

sometimes we

require to solve

“change in state”

Say Any State

Machines

Points to Note

In the case of Apple Filter, The Behaviour being passed as parameter carries “expression” of apple colour check or apple weight check to be evaluated lazily.

In the case of Wall Class, when you create Wall, the Behaviour being passed as parameter carries “value” to set the state of the object lazily.

Hurrah!!!We have done with our basics concepts

Behaviour Passing with Lambdas

In order to pass parameterize behaviours, we might have created “New Classes” either concrete or anonymous. In Java 8, we can use Lambdas to pass changing behaviours.

Behaviour Passing with LambdasBefore Java 8

After Java 8

Lambda Expression

Anonymous Class instead of Separate Class

Stage 1 - Completed

STAGE 2

Basics of Pure Functions.Mathematical Functions mapping between Domains.

It may not be familiar

to you.At the end,You may have made a

Jump, yet not reached

required Height…

FUNCTIONS

• Functions are nothing but passable Behaviours. They are not methods. They may be “expression” or “value” as said before.

• FP is all about these functions • Lambda Expression is Concise form of

Functions.• A method can act as function when it is an

“expression” or a “value”.

FUNCTIONAL PROGRAMMING

Lambda Expression is a Pure Function

Z= X+YF(Z) = 2Z+3Z

After Z expression replacement F(Z) is not

affectedF(X+Y)= 2(X+Y)+3(X+Y)

A SIMPLE Equational Reasoning

FUNCTIONAL PROGRAMMING

FUNCTIONAL PROGRAMMING

FUNCTIONAL PROGRAMMING

FUNCTIONAL PROGRAMMING

Stage 2 - Completed

STAGE 3

Back to programming.Once more Concept – “Partial Application”

Back to Earth…At the end,You are Ready for an

another Jump to reach more height …

With more Momentum…

A SIMPLE CONVERTOR UTILITY

Everything works fine, we observe across conversion here the “base” and “factor” alone need to be changed for creating different conversion Behaviours.

We create a Strategy like before.

Partial Application

Here You can see that we have “Partially Applied” Our Parameters “Base”& “Factors” in their respective Strategy and we have created a “Behaviour Parameterization”

Consider, We are partially passing a part of the complete “expression”, and the rest of the “expression” is already applied/present.

Partial Application

Jump 2

Jump 3

This expression looks like a math expression, a pure function!!!

From Simple Utility to Strategy

Jump 1

Stage 3 - Completed

Points to Note

• We achieved Modularity.• We applied 2 parameter to create Strategy.• We have a Problem over here, we have lot of

Anonymous classes or Lambda expression.

STAGE 4

More Programming…More Abstraction… More Modularity…

Jump to reach more

height …With more Momentum…

Reusing Lambdas

Now Lambda Expression have been reused

More HelpersMore Helpers likeApply Factor,Apply Base

And

Two Weird looking Methods

The Weird LookingMethods are for FPFunction Composition

Parameters Passing

Applying Parameters one by one

Removed unnecessary parameters

LAMBDA EXPRESSION – EXPRESSIONS FOR ANONYMOUS PURE FUNCTION Sqsum(x,y) = x * x + y * y; // Pure Function lambda Expression: (x,y) -> x *x+y*y // Lambda Expression

Evaluation with (5, 6) will take place by currying & partial application like( (x,y) -> x *x+y*y ) (5,6) // with input parameters((x->(y->x *x+y*y))(5))(6) // Curried or Currying (y->5*5+y*y)(6) // Partially Applied -> new function obtained.5*5+6*6 // complete application of parameters61

LAMBDA EXPRESSIONS

Stage 4 - CompletedWe have Just seen a

Glimpse of FP

Why Lambdas & Functional Programming?

Increasingly dealing with big data (terabytes and up) and wishing to exploit multicore computers or computing clusters effectively to process data.

And this means using:

parallel processing FP Makes this Concern to be handled very easily.

big data multicore cloud computing IoT

THE CHANGING COMPUTING BACKGROUND – THE CLIMATE CHANGE

There has been a lot of progress &

Progress is being allowed to forget things or leaving it for others concern ;)

THE PROGRESS OF PROGRAMMING

There`s been a lot of progress:

- Assemblers let us forget about opcodes

THE PROGRESS OF PROGRAMMING

There`s been a lot of progress:

- Assemblers let us forget opcodes- Garbage collections let us forget memory management

#include <stdio.h> #include <stdlib.h> int main () {…

buffer = (char*) malloc (i+1); …

free (buffer);…}

THE PROGRESS OF PROGRAMMING

So what about parallelism?

THE PROGRESS OF PROGRAMMING

Most of parallelism problems are doing bulk operations on collectionand we keep writing code like this:

int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; }

It is inherently serial

CURRENT STATE OF PARALLELISM & CONCURRENCY

CURRENT STATE OF PARALLELISM & CONCURRENCY

If the processing of different elements is to proceed in parallel, now it is the responsibility of the client code

n1 n2 n3 n4 n5 n6 n7 n8 n9 … … … …

sum1 sum2 sum3 sum4

CURRENT STATE OF PARALLELISM & CONCURRENCY

If the processing of different elements is to proceed in parallel, now it is the responsibility of the client code

n1 n2 n3 n4 n5 n6 n7 n8 n9 … … … …

class Sum implements Callable<Long> {private final long from;private final long to;Sum(long from, long to) {

this.from = from;this.to = to;

}public Long call() {

long acc = 0;for (long i = from; i <= to; i++) {

acc = acc + i;}return acc;}

}

sum1 sum2 sum3 sum4

CURRENT STATE OF PARALLELISM & CONCURRENCY

If the processing of different elements is to proceed in parallel, now it is the responsibility of the client code

n1 n2 n3 n4 n5 n6 n7 n8 n9 … … … …

sum1 sum2 sum3 sum4

ExecutorService executor = Executors.newFixedThreadPool(2);List<Future<Long>> results = executor.invokeAll(asList(

new Sum(1, 250),new Sum(251, 500),new Sum(551, 750),new Sum(751, 1000)

));for (Future<Long> result : results) {

System.out.println(result.get());}

Partitioning of data from 1-250, 251-500 etc can

also be done withJava 7 - Fork/Join

Framework (take cares of Partitioning based on

processor availability with job stealing algorithm)

CURRENT STATE OF PARALLELISM & CONCURRENCY

If the processing of different elements is to proceed in parallel, now it is the responsibility of the client code

Java 8 has a solution for this Problem and it will let us forget Parallel Processing at required extend .

Driven By the concepts1. Functional Programming2. No shared mutable data -> Immutability3. Behavior Parameterization (Passing code / Anonymous Pure

Functions as parameters). 4. Stream Processing - > Immutable Data Structures - favoring Internal

Iteration over External Iteration.

CURRENT STATE OF PARALLELISM & CONCURRENCY

THE CHANGING DEVELOPMENT BACKGROUND IS THE CLIMATE CHANGE

Conway’s law Any organization that designs a system (defined more broadly here

than just information systems) will inevitably produce a design whose structure is a copy of the organization's communication

structure.

THE CHANGING DEVELOPMENT BACKGROUND IS THE CLIMATE CHANGE

Onion Architecture

THE CHANGING DEVELOPMENT BACKGROUND IS THE CLIMATE CHANGE

Pure functions are ideal candidates for reactive modelling because you can freelydistribute them in a parallel setting without any concern for managing mutable sharedstate. This is really where functional meets reactive.

Event based programming delineates the “what” from the “how” of your model. Andthis is also what functional programming encourages. Events are small messages thatspecify what you want to do, and the handler for the event describes the how part. Nowonder functional programming and event driven programming play well together.

With functional design and thinking your model grows organically, and by virtue ofbeing pure you can treat your model mathematically and reason about it.

Building a DSL or Domain Algebra is easier with FP.

Functional Programming brings in the Necessary Agility required.

“OOPS bind State & Behaviours, FP Decouples State & Behaviours”

FUNCTIONAL PROGRAMMING

Explore More FP!!!

Q & A

Thank You