functional programming in java

56
Functional Programming in Java Narendran, S S

Upload: narendran-solai-sridharan

Post on 15-Feb-2017

183 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Functional Programming in Java

Functional Programming in Java

Narendran, S S

Page 2: Functional Programming in Java

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

Page 3: Functional Programming in Java

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

Page 4: Functional Programming in Java

We need to move Out of OOPBox

Are We Ready to Jump out of OOP Box?

Page 5: Functional Programming in Java

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…

Page 6: Functional Programming in Java

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

Page 7: Functional Programming in Java

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.

Page 8: Functional Programming in Java

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

Page 9: Functional Programming in Java

• Change: Add a Support to filter apples by Weight

Page 10: Functional Programming in Java

• Change: More Changes

The Code Bloats

Page 11: Functional Programming in Java

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

changes happens?

Page 12: Functional Programming in Java

Refinement 1: Creating a Strategy

Page 13: Functional Programming in Java

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

This is called “Behavioural Parameterization”

Hurrah!!!

Page 14: Functional Programming in Java

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

Page 15: Functional Programming in Java

Next: Lazy Evaluation & Lazy Initialization.

Next?

Page 16: Functional Programming in Java

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”

Page 17: Functional Programming in Java

Lazy Initialization

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

Page 18: Functional Programming in Java

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

Page 19: Functional Programming in Java

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

Page 20: Functional Programming in Java

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.

Page 21: Functional Programming in Java

Behaviour Passing with LambdasBefore Java 8

After Java 8

Lambda Expression

Anonymous Class instead of Separate Class

Stage 1 - Completed

Page 22: Functional Programming in Java

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…

Page 23: Functional Programming in Java

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”.

Page 24: Functional Programming in Java

FUNCTIONAL PROGRAMMING

Lambda Expression is a Pure Function

Page 25: Functional Programming in Java

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

Page 26: Functional Programming in Java

FUNCTIONAL PROGRAMMING

Page 27: Functional Programming in Java

FUNCTIONAL PROGRAMMING

Page 28: Functional Programming in Java

FUNCTIONAL PROGRAMMING

Stage 2 - Completed

Page 29: Functional Programming in Java

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…

Page 30: Functional Programming in Java

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.

Page 31: Functional Programming in Java

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.

Page 32: Functional Programming in Java

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

Page 33: Functional Programming in Java

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.

Page 34: Functional Programming in Java

STAGE 4

More Programming…More Abstraction… More Modularity…

Jump to reach more

height …With more Momentum…

Page 35: Functional Programming in Java

Reusing Lambdas

Now Lambda Expression have been reused

Page 36: Functional Programming in Java

More HelpersMore Helpers likeApply Factor,Apply Base

And

Two Weird looking Methods

The Weird LookingMethods are for FPFunction Composition

Page 37: Functional Programming in Java

Parameters Passing

Applying Parameters one by one

Removed unnecessary parameters

Page 38: Functional Programming in Java

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

Page 39: Functional Programming in Java

Why Lambdas & Functional Programming?

Page 40: Functional Programming in Java

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

Page 41: Functional Programming in Java

There has been a lot of progress &

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

THE PROGRESS OF PROGRAMMING

Page 42: Functional Programming in Java

There`s been a lot of progress:

- Assemblers let us forget about opcodes

THE PROGRESS OF PROGRAMMING

Page 43: Functional Programming in Java

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

Page 44: Functional Programming in Java

So what about parallelism?

THE PROGRESS OF PROGRAMMING

Page 45: Functional Programming in Java

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

Page 46: Functional Programming in Java

CURRENT STATE OF PARALLELISM & CONCURRENCY

Page 47: Functional Programming in Java

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

Page 48: Functional Programming in Java

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

Page 49: Functional Programming in Java

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

Page 50: Functional Programming in Java

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

Page 51: Functional Programming in Java

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.

Page 52: Functional Programming in Java

THE CHANGING DEVELOPMENT BACKGROUND IS THE CLIMATE CHANGE

Onion Architecture

Page 53: Functional Programming in Java

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.

Page 54: Functional Programming in Java

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

FUNCTIONAL PROGRAMMING

Explore More FP!!!

Page 55: Functional Programming in Java

Q & A

Page 56: Functional Programming in Java

Thank You