SlideShare a Scribd company logo
1 of 21
Download to read offline
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

Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
Derek Dhammaloka
 
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
 

What's hot (20)

Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
 
Removal Of Recursion
Removal Of RecursionRemoval Of Recursion
Removal Of Recursion
 
Functional Reactive Programming
Functional Reactive ProgrammingFunctional Reactive Programming
Functional Reactive Programming
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
 
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
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
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
 
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
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 
Java -lec-5
Java -lec-5Java -lec-5
Java -lec-5
 
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
 
Mcrl2 by kashif.namal@gmail.com, adnanskyousafzai@gmail.com
Mcrl2 by kashif.namal@gmail.com, adnanskyousafzai@gmail.comMcrl2 by kashif.namal@gmail.com, adnanskyousafzai@gmail.com
Mcrl2 by kashif.namal@gmail.com, adnanskyousafzai@gmail.com
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Towards hasktorch 1.0
Towards hasktorch 1.0Towards hasktorch 1.0
Towards hasktorch 1.0
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
 

Viewers also liked

Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
IIUM
 

Viewers also liked (20)

Maintainability of Configuration Management Code
Maintainability of Configuration Management CodeMaintainability of Configuration Management Code
Maintainability of Configuration Management Code
 
Coding convention
Coding conventionCoding convention
Coding convention
 
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
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in Clojure
 
Wdrozenie rodo krok po kroku
Wdrozenie rodo krok po krokuWdrozenie rodo krok po kroku
Wdrozenie rodo krok po kroku
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with Clojure
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
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?
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Stateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWTStateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWT
 
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!
 
Core FP Concepts
Core FP ConceptsCore FP Concepts
Core FP Concepts
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
 
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
 
JavaStart - kurs Java Podstawy
JavaStart - kurs Java PodstawyJavaStart - kurs Java Podstawy
JavaStart - kurs Java Podstawy
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8
 
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...
 
Ada 95 - Structured programming
Ada 95 - Structured programmingAda 95 - Structured programming
Ada 95 - Structured programming
 
Good Programming Practice
Good Programming PracticeGood Programming Practice
Good Programming Practice
 
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
 

Similar to Functional Programming in Java - Code for Maintainability

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

Java 8
Java 8Java 8
Java 8
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
 
java8
java8java8
java8
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Java 8 - functional features
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional features
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Oct.22nd.Presentation.Final
Oct.22nd.Presentation.FinalOct.22nd.Presentation.Final
Oct.22nd.Presentation.Final
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
 
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
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8
 
Actor, an elegant model for concurrent and distributed computation
Actor, an elegant model for concurrent and distributed computationActor, an elegant model for concurrent and distributed computation
Actor, an elegant model for concurrent and distributed computation
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul JindalOverview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
 
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul JindalOverview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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