SlideShare a Scribd company logo
Functional Programming in Java
Code For Maintainability
1
KrkDataLink
Kraków
2017-02-15
@marcinstepien
www.smart.biz.pl
Marcin Stepien
Developer, Consultant
@marcinstepien
www.smart.biz.pl
2005
www.whenvi.com
2014
2
What is here
3
Code for maintainability
Functional Programing intro
Object vs Functional
Code examples
So the next developer doesn’t hate you
Code For Maintainability
4
Maintainable Code
5
Reusable Expressive
Clear > Clever Separate of concerns
Closure Lisp
Frege kind of Haskell
Scala
Java 8, Kotlin, Groovy
Functional Programming on
JVM
6
Functional
Programming
Java
7
➔ Streams
➔ Lambda expressions
➔ Functions as first class citizens
➔ Functional Interfaces
8
Java 8 FP
➔ No side effects
➔ Final variables
➔ y = f(x) always same y for given x
9
(pure) function
Function<Integer,Integer> increase = x -> x + 1;
#parameter -> body
10
Java 8 function
11
Functional interface Function descriptor
Predicate<T> T -> boolean
Consumer<T> T -> void
Function<T,R> T -> R
Supplier<T> () -> T
UnaryOperator<T> T -> T
BinaryOperator<T> (T,T) -> T
BiPredicate<L,R> (L,R) -> boolean
BiConsumer<T,U> (T,U) -> void
BiFunction<T,U,R> (T,U) -> R
#instead of
Runnable task =
new Runnable() {
public void run() {
System.out.println(”no arg consumer” )
}
}
12
Replace ceremony with Lambda
Runnable task =
() -> { System.out.println(”no arg consumer” ); };
13
Internal iterators
#instead of loops
for(String name : names) {
System.out.println(name)
}
#use internal iterators
names.forEach(e -> System.out.println(e))
#with method reference
names.forEach(System.out::println)
public int getSumOfEvens(List<Integer> nums){
Integer sum = 0;
for(Integer num : nums) {
if(num != null && num % 2 == 0) {
sum += num;
}
}
return sum;
}
14
Fight verbosity with streams
nums.stream()
.filter(Objects::nonNull)
.filter( number -> number % 2 == 0)
.reduce(0, Integer::sum);
15
Passing functions
public int
getSum(List<Integer>nums,Predicate<Integer> filter,
Bifunction<Integer,Integer,Integer> accumulator)
{
return nums.stream()
.filter(filter)
.filter(Objects::nonNull)
.reduce(0, accumulator);
}
Predicate<Integer> isEven = n -> n % 2 == 0;
int sum = getSum(numbers, isEven, Integer::sum);
16
Map reduce, lazy evaluation
public int getTranactions(List<User> users) {
return users.stream() # or parallelStream()
.filter(u -> u.isActivated())
.map( u -> u.getTranTotal())
.reduce(0, Integer::sum);} #terminal op
public Stream<Integer> get(List<User> users) {
#no computation is happening here
return users.stream()
.filter(u -> u.isActivated())
.map( u -> u.getTranTotal());
}
17
Lazy evaluation, infinite series
Stream<Integer> infiniteSeries
= Stream.iterate(1, e -> e + 1)
18
Slimmer patterns: decorator
← https://en.wikipedia.org/wiki/Decorator_pattern#Second_example_.28coffee_making_scenario.29
← Hierarchy of types
can be replaced with Function Composition:
● .compose(Function f)
● .andThan(Function f)
19
Function composition
class Barista {
public static Coffee makeCoffee
(Coffee baseCoffee,
Function<Coffee, Coffee>... addIngredients)
{
return Stream.of(addIngredients)
.reduce(
Function.<Coffee>identity(),
//or Function::andThan
(addIngr1, addIngr2) -> addIngr1.andThan(addIngr2))
Coffee coffee = Barista.makeCoffee(
new Arabica(),
Coffee::withMilk,
Coffee::withSprinkles));
Object vs Functional
20
● Imperative
● Mutability
● Lower abstraction
● Reveals impl. details
● Eager by default
● nulls
● Hierarchy of types
● Declarative
● Favors Immutability
● Expressive
● Hides impl. details
● Lazy by default
● Optionals
● Function composition
marcin@smart.biz.pl
@marcinstepien
21
Thank you

More Related Content

What's hot (20)

Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
Rumman Ansari
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
Patrick Viafore
 
Removal Of Recursion
Removal Of RecursionRemoval Of Recursion
Removal Of Recursion
Richa Sharma
 
Functional Reactive Programming
Functional Reactive ProgrammingFunctional Reactive Programming
Functional Reactive Programming
Felipe Hernández Rivas
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Brainhub
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
Derek Dhammaloka
 
Formal methods Project Report for the support of slides uploaded
Formal methods Project Report for the support of slides uploaded Formal methods Project Report for the support of slides uploaded
Formal methods Project Report for the support of slides uploaded
Shoaib Haseeb
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
Introduction to Computer and Programing - Lecture 04
Introduction to Computer and Programing - Lecture 04Introduction to Computer and Programing - Lecture 04
Introduction to Computer and Programing - Lecture 04
hassaanciit
 
Check the output of the following code then recode it to eliminate fu
 Check the output of the following code then recode it to eliminate fu Check the output of the following code then recode it to eliminate fu
Check the output of the following code then recode it to eliminate fu
licservernoida
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
Java -lec-5
Java -lec-5Java -lec-5
Java -lec-5
Zubair Khalid
 
2015.3.12 the root of lisp
2015.3.12 the root of lisp2015.3.12 the root of lisp
2015.3.12 the root of lisp
Chung-Hsiang Ofa Hsueh
 
Mcrl2 by [email protected], [email protected]
Mcrl2 by kashif.namal@gmail.com, adnanskyousafzai@gmail.comMcrl2 by kashif.namal@gmail.com, adnanskyousafzai@gmail.com
Mcrl2 by [email protected], [email protected]
kashif kashif
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
Yuriy Bondaruk
 
Towards hasktorch 1.0
Towards hasktorch 1.0Towards hasktorch 1.0
Towards hasktorch 1.0
Junji Hashimoto
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
Outware Mobile
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
Colin Eberhardt
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
Rumman Ansari
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
Patrick Viafore
 
Removal Of Recursion
Removal Of RecursionRemoval Of Recursion
Removal Of Recursion
Richa Sharma
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Brainhub
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
Derek Dhammaloka
 
Formal methods Project Report for the support of slides uploaded
Formal methods Project Report for the support of slides uploaded Formal methods Project Report for the support of slides uploaded
Formal methods Project Report for the support of slides uploaded
Shoaib Haseeb
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
Introduction to Computer and Programing - Lecture 04
Introduction to Computer and Programing - Lecture 04Introduction to Computer and Programing - Lecture 04
Introduction to Computer and Programing - Lecture 04
hassaanciit
 
Check the output of the following code then recode it to eliminate fu
 Check the output of the following code then recode it to eliminate fu Check the output of the following code then recode it to eliminate fu
Check the output of the following code then recode it to eliminate fu
licservernoida
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
Yuriy Bondaruk
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
Outware Mobile
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
Colin Eberhardt
 

Viewers also liked (20)

Maintainability of Configuration Management Code
Maintainability of Configuration Management CodeMaintainability of Configuration Management Code
Maintainability of Configuration Management Code
Clinton Wolfe
 
Coding convention
Coding conventionCoding convention
Coding convention
Thành Nguyễn
 
Play Framework on Google App Engine - Productivity Stack
Play Framework on Google App Engine - Productivity StackPlay Framework on Google App Engine - Productivity Stack
Play Framework on Google App Engine - Productivity Stack
Marcin Stepien
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in Clojure
Troy Miles
 
Wdrozenie rodo krok po kroku
Wdrozenie rodo krok po krokuWdrozenie rodo krok po kroku
Wdrozenie rodo krok po kroku
PwC Polska
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with Clojure
John Stevenson
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
Francesco Bruni
 
Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?
Netguru
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Stateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWTStateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWT
Gaurav Roy
 
Uses of Cupcakes For Any Occasion in Hyderabad!
 Uses of Cupcakes For Any Occasion in Hyderabad! Uses of Cupcakes For Any Occasion in Hyderabad!
Uses of Cupcakes For Any Occasion in Hyderabad!
bookthecake.com
 
Core FP Concepts
Core FP ConceptsCore FP Concepts
Core FP Concepts
Diego Pacheco
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
IIUM
 
Oop project briefing sem 1 2015 2016
Oop project briefing  sem 1 2015 2016Oop project briefing  sem 1 2015 2016
Oop project briefing sem 1 2015 2016
IIUM
 
JavaStart - kurs Java Podstawy
JavaStart - kurs Java PodstawyJavaStart - kurs Java Podstawy
JavaStart - kurs Java Podstawy
JavaStart
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8
Dragos Balan
 
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
yaminohime
 
Ada 95 - Structured programming
Ada 95 - Structured programmingAda 95 - Structured programming
Ada 95 - Structured programming
Gneuromante canalada.org
 
Good Programming Practice
Good Programming PracticeGood Programming Practice
Good Programming Practice
Bikalpa Gyawali
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming LanguageWhy C is Called Structured Programming Language
Why C is Called Structured Programming Language
Sinbad Konick
 
Maintainability of Configuration Management Code
Maintainability of Configuration Management CodeMaintainability of Configuration Management Code
Maintainability of Configuration Management Code
Clinton Wolfe
 
Play Framework on Google App Engine - Productivity Stack
Play Framework on Google App Engine - Productivity StackPlay Framework on Google App Engine - Productivity Stack
Play Framework on Google App Engine - Productivity Stack
Marcin Stepien
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in Clojure
Troy Miles
 
Wdrozenie rodo krok po kroku
Wdrozenie rodo krok po krokuWdrozenie rodo krok po kroku
Wdrozenie rodo krok po kroku
PwC Polska
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with Clojure
John Stevenson
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
Francesco Bruni
 
Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?
Netguru
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Stateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWTStateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWT
Gaurav Roy
 
Uses of Cupcakes For Any Occasion in Hyderabad!
 Uses of Cupcakes For Any Occasion in Hyderabad! Uses of Cupcakes For Any Occasion in Hyderabad!
Uses of Cupcakes For Any Occasion in Hyderabad!
bookthecake.com
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
IIUM
 
Oop project briefing sem 1 2015 2016
Oop project briefing  sem 1 2015 2016Oop project briefing  sem 1 2015 2016
Oop project briefing sem 1 2015 2016
IIUM
 
JavaStart - kurs Java Podstawy
JavaStart - kurs Java PodstawyJavaStart - kurs Java Podstawy
JavaStart - kurs Java Podstawy
JavaStart
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8
Dragos Balan
 
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
yaminohime
 
Good Programming Practice
Good Programming PracticeGood Programming Practice
Good Programming Practice
Bikalpa Gyawali
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming LanguageWhy C is Called Structured Programming Language
Why C is Called Structured Programming Language
Sinbad Konick
 
Ad

Similar to Functional Programming in Java - Code for Maintainability (20)

Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional Programming
Aapo Kyrölä
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
coriehokitiw
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
Jayaram Sankaranarayanan
 
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
romergalbowx
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good Practices
Naresha K
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
Kazuhiro Sera
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Hugo Firth
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
Narendran Solai Sridharan
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
felixtrepanier
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
Fp java8
Fp java8Fp java8
Fp java8
Yanai Franchi
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional Programming
Aapo Kyrölä
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
Functional Programming In Java Harnessing The Power Of Java 8 Lambda Expressi...
coriehokitiw
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
Jayaram Sankaranarayanan
 
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
A Functional Approach to Java: Augmenting Object-Oriented Java Code with Func...
romergalbowx
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good Practices
Naresha K
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
Kazuhiro Sera
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Hugo Firth
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
felixtrepanier
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
Ad

Recently uploaded (20)

Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 

Functional Programming in Java - Code for Maintainability

  • 1. Functional Programming in Java Code For Maintainability 1 KrkDataLink Kraków 2017-02-15 @marcinstepien www.smart.biz.pl
  • 3. What is here 3 Code for maintainability Functional Programing intro Object vs Functional Code examples
  • 4. So the next developer doesn’t hate you Code For Maintainability 4
  • 5. Maintainable Code 5 Reusable Expressive Clear > Clever Separate of concerns
  • 6. Closure Lisp Frege kind of Haskell Scala Java 8, Kotlin, Groovy Functional Programming on JVM 6
  • 8. ➔ Streams ➔ Lambda expressions ➔ Functions as first class citizens ➔ Functional Interfaces 8 Java 8 FP
  • 9. ➔ No side effects ➔ Final variables ➔ y = f(x) always same y for given x 9 (pure) function
  • 10. Function<Integer,Integer> increase = x -> x + 1; #parameter -> body 10 Java 8 function
  • 11. 11 Functional interface Function descriptor Predicate<T> T -> boolean Consumer<T> T -> void Function<T,R> T -> R Supplier<T> () -> T UnaryOperator<T> T -> T BinaryOperator<T> (T,T) -> T BiPredicate<L,R> (L,R) -> boolean BiConsumer<T,U> (T,U) -> void BiFunction<T,U,R> (T,U) -> R
  • 12. #instead of Runnable task = new Runnable() { public void run() { System.out.println(”no arg consumer” ) } } 12 Replace ceremony with Lambda Runnable task = () -> { System.out.println(”no arg consumer” ); };
  • 13. 13 Internal iterators #instead of loops for(String name : names) { System.out.println(name) } #use internal iterators names.forEach(e -> System.out.println(e)) #with method reference names.forEach(System.out::println)
  • 14. public int getSumOfEvens(List<Integer> nums){ Integer sum = 0; for(Integer num : nums) { if(num != null && num % 2 == 0) { sum += num; } } return sum; } 14 Fight verbosity with streams nums.stream() .filter(Objects::nonNull) .filter( number -> number % 2 == 0) .reduce(0, Integer::sum);
  • 15. 15 Passing functions public int getSum(List<Integer>nums,Predicate<Integer> filter, Bifunction<Integer,Integer,Integer> accumulator) { return nums.stream() .filter(filter) .filter(Objects::nonNull) .reduce(0, accumulator); } Predicate<Integer> isEven = n -> n % 2 == 0; int sum = getSum(numbers, isEven, Integer::sum);
  • 16. 16 Map reduce, lazy evaluation public int getTranactions(List<User> users) { return users.stream() # or parallelStream() .filter(u -> u.isActivated()) .map( u -> u.getTranTotal()) .reduce(0, Integer::sum);} #terminal op public Stream<Integer> get(List<User> users) { #no computation is happening here return users.stream() .filter(u -> u.isActivated()) .map( u -> u.getTranTotal()); }
  • 17. 17 Lazy evaluation, infinite series Stream<Integer> infiniteSeries = Stream.iterate(1, e -> e + 1)
  • 18. 18 Slimmer patterns: decorator ← https://en.wikipedia.org/wiki/Decorator_pattern#Second_example_.28coffee_making_scenario.29 ← Hierarchy of types can be replaced with Function Composition: ● .compose(Function f) ● .andThan(Function f)
  • 19. 19 Function composition class Barista { public static Coffee makeCoffee (Coffee baseCoffee, Function<Coffee, Coffee>... addIngredients) { return Stream.of(addIngredients) .reduce( Function.<Coffee>identity(), //or Function::andThan (addIngr1, addIngr2) -> addIngr1.andThan(addIngr2)) Coffee coffee = Barista.makeCoffee( new Arabica(), Coffee::withMilk, Coffee::withSprinkles));
  • 20. Object vs Functional 20 ● Imperative ● Mutability ● Lower abstraction ● Reveals impl. details ● Eager by default ● nulls ● Hierarchy of types ● Declarative ● Favors Immutability ● Expressive ● Hides impl. details ● Lazy by default ● Optionals ● Function composition