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

Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structureRumman 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 RecursionRicha Sharma
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressionsDerek 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 JQKnoldus 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 04hassaanciit
 
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 fulicservernoida
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a BossBob Tiernay
 
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.comkashif kashif
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in PracticeOutware Mobile
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7Rumman Ansari
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftColin Eberhardt
 

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

Maintainability of Configuration Management Code
Maintainability of Configuration Management CodeMaintainability of Configuration Management Code
Maintainability of Configuration Management CodeClinton 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 StackMarcin Stepien
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in ClojureTroy Miles
 
Wdrozenie rodo krok po kroku
Wdrozenie rodo krok po krokuWdrozenie rodo krok po kroku
Wdrozenie rodo krok po krokuPwC Polska
 
Get into Functional Programming with Clojure
Get into Functional Programming with ClojureGet into Functional Programming with Clojure
Get into Functional Programming with ClojureJohn Stevenson
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approachFrancesco 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 ProgrammingShine Xavier
 
Stateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWTStateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWTGaurav 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-paradigmIIUM
 
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 2016IIUM
 
JavaStart - kurs Java Podstawy
JavaStart - kurs Java PodstawyJavaStart - kurs Java Podstawy
JavaStart - kurs Java PodstawyJavaStart
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8Dragos 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 PracticeBikalpa 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 LanguageSinbad Konick
 

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

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 IndicThreads
 
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 fpAlexander Granin
 
Java 8 - functional features
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional featuresRafal Rybacki
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015senejug
 
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 DevelopersJayaram Sankaranarayanan
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#Giorgio Zoppi
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Madina Kamzina
 
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 computationAlessio Coltellacci
 
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 smartChen Fisher
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
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 JindalArvind Surve
 
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 JindalArvind Surve
 
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 APIJörn Guy Süß JGS
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 

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

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

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