SlideShare a Scribd company logo
1 of 53
Download to read offline
JavazJavaz
Functional designFunctional design
in Java 8in Java 8
IntroIntro
All Java code can be found at Javaz
https://github.com/escalate42/Javaz
The emergence of native support for lambdas in Java 8
has opened the possibility to adapt the rich experience
of statically typed functional programming languages to
the Java world. So the Javaz appears.
finally!This presentation can be found at
https://slides.com/vadimdubs/javaz​
Common functionalCommon functional
programming patternsprogramming patterns
Functor
ApplicativeFunctor
Monad
First appeared in Haskell programing langugage
TypeclassesTypeclasses
First appeared in Haskell programing langugage
Is a sort of interface that defines some behavior
You can think of them kind of as Java interfaces
-- Typeclass definition with name Eq, type variable a
-- and function == which has two params of type a and
-- returns Bool
class Eq a where
eq :: a -> a -> Bool
-- Data Type definition (like Java enum in this case)
data TrafficLight = Red | Yellow | Green
-- Instance definition for TrafficLight data type and
-- Eq typeclass
instance Eq TrafficLight where
eq Red Red = True
eq Yellow Yellow = True
eq Green Green = True
eq _ _ = False
public interface Eq<A> {
public boolean eq(A other);
}
public final class TrafficLight implements Eq<TrafficLight> {
public static TrafficLight RED = new TrafficLight();
public static TrafficLight YELLOW = new TrafficLight();
public static TrafficLight GREEN = new TrafficLight();
private TrafficLight() {}
@Override
public boolean eq(TrafficLight other) {
return other == this;
}
}
FunctionFunction
@FunctionalInterface
interface Function<A, B> {
B apply(A a);
}
Function<A, B> function1 = Functions::function;
Function<A, B> function2 = a -> new B(a);
function :: a -> b
@FunctionalInterface
interface Function<A, B> {
B apply(A a);
}
Function<A, B> f;
Function<B, C> g;
static <A, B, C> Function<A, C> compose(
Function<A, B> ab, Function<B, C> bc
) {
return a -> bc.apply(ab.apply(a));
}
Function<A, C> h = compose(f, g);
f :: a -> b
g :: b -> c
. :: (a -> b) -> (b -> c) -> a -> c
f1 . f2 = x -> f2 (f1 x)
h :: a -> c
h = f . g
FunctorFunctor
for things that can be mapped over.
class Functor F where
fmap :: (a -> b) -> F a -> F b
data Maybe a = Just a | Nothing
FunctorFunctor
for things that can be mapped over.
class Functor F where
fmap :: (a -> b) -> F a -> F b
Applicative FunctorApplicative Functor
class (Functor F) => Applicative F where
pure :: a -> F a
(<*>) :: F (a -> b) -> F a -> F b
Applicative FunctorApplicative Functor
class (Functor F) => Applicative F where
pure :: a -> F a
(<*>) :: F (a -> b) -> F a -> F b
MonadMonad
class Monad M where
return :: a -> M a
(>>=) :: M a -> (a -> M b) -> M b
MonadMonad
class Monad M where
return :: a -> M a
(>>=) :: M a -> (a -> M b) -> M b
f :: a -> M a
g :: a -> M b
-- Bind function
(>>=) :: M a -> (a -> M b) -> M b
a -> (f a) >>= a -> (g a)
-- Same in term of types
-- (>>=) is the same as
-- composition of functions
(a -> M a) >>= (a -> M b)
-- Composition of functions
(a -> a) . (a -> b)
CommonCommon
implementationsimplementations
Collection - container for a group of
values
Option/Maybe​ - for optional values
Either - for results that either success or
failure
Future - for async computations
OptionOption
For optional values, typesafe way to avoid null and null-checks
Option<T> always is in one of two states:
Some<T> - simple container for value of type T
None<T> - represents absence of any value of type T
Javaz implementation
User auth(String l, String p);
Role getRole(User u);
Permissions getPermissions(Role r);
List<Partner> getPartners(Permissions p);
User user = auth("user", "password");
Role role = null;
Permissions permissions = null;
List<Partner> partners = new ArrayList<>();
if (user != null) {
role = getRole(user);
}
if (role != null) {
permissions = getPermissions(role);
}
if (permissions != null) {
partners.addAll(getPartners(permissions));
}
Function2<String, String, Option<User>> auth;
Function<User, Option<Role>> getRole;
Function<Role, Option<Permissions>> getPermissions;
Function<Permissions, List<Partner>> getPartners;
List<Partner> partners =
// trying to authenticate user
auth.apply("login", "password")
// trying to get Role for this
// user from service via http
.flatMap(getRole) // the same as >>=
// trying to load permissions
// from database
.flatMap(getPermissions)
// trying to load partners from
// another data source
.map(getPartners) // the same as fmap
.getOrElse(new ArrayList());
OptionalOptional
import static Optional.of;
import static Optional.empty;
final Optional<Integer> first = of(3);
final Optional<Integer> second = of(4);
final Optional<Integer> empty = empty();
// Optional is a functor and monad
first.map(i -> i * i) // Some(9)
empty.map(i -> i * i) // None
first.flatMap(f -> second.map(s -> f + s));
// Some(7)
first.flatMap(f -> empty.map(s -> f + s));
// None
Implementation from standard Java 8 library
EitherEither
For results that either success or failure, typesafe way to avoid
usege of exceptions.
Has no analogs in standard Java library.
Either<L, R> always is in one of two states:
Right<L, R> - container for value of type R
Left<L, R> - container for values of type L that represents some
failure
Javaz implementation
F2<String, String, Either<ErrorInfo, User>> auth;
F<User, Either<ErrorInfo, Role>> getRole;
F<Role, Either<ErrorInfo, Permissions>> getPermissions;
F<Permissions, List<Partner>> getPartners;
Either<ErrorInfo, List<Partner>> eitherPartners =
// trying to authenticate user
auth.apply("login", "password")
// trying to get Role for this
// user from service via http
.fmap(getRole)
// trying to load permissions
// from database
.fmap(getPermissions)
// trying to load partners from
// another data source
.map(getPartners);
eitherPartners.mapLeft(logger::error);
List<String> partnerNames = eitherPartners.foldRight(
new ArrayList(), partner -> partner.getName
)
StreamStream
final Stream<Integer> stream =
Arrays.asList(1, 2, 3, 4, 5).stream();
// Streams are functors
stream.map(i -> i + 1);
// [2, 3, 4, 5, 6]
stream.forEach(System.out::print);
// out > 12345
Implementation from standard Java 8 library
StreamStream
final Stream<Integer> stream
= Arrays.asList(1, 2, 3, 4, 5).stream();
// Streams are monads
stream.flatMap(
i -> Arrays.asList(i + 1, i + 2).stream()
);
// [2, 3, 3, 4, 4, 5, 5, 6, 6, 7]
Implementation from standard Java 8 library
StreamStream
Function<User, Stream<Permission>> permissionsByUser;
Function<Permission, Stream<Partner>> partnersByPermissions;
Stream<User> users = Arrays.asList(user1, user2).stream();
Set<Partners> availablePartners = users
.flatMap(permissionByUser)
// get all permissions of user 1 and user2
.distinct()
// left only unique items
.flatMap(partnersByPermissions)
// get all partners available through permissions
.collect(Collectors.toSet);
Implementation from standard Java 8 library
FutureFuture
Javaz implementation
Function2<String, String, Future<User>> auth;
Function<User, Future<Stream<User>>> getFriends;
Function<User, Stream<Group>> getGroups;
Future<User> user = auth.apply("login", "password");
Future<Stream<Group>> myGroups = user.map(getGroups)
Future<Stream<User>> friendsGroups = user
.flatMap(getFriends)
.map(Stream::flatMap(getGroups).distinct());
Future<Set<Group>> uniqueFriendsGroups = yieldFor(
myGroups, myFirends, (myGroups, firendsGroups) ->
friendsGroups.collect(toSet)
.removeAll(myGroups.collect(toSet))
)
uniqueFriendsGroups.get(100, TimeUnit.MILLISECONDS)
CompletableFutureCompletableFuture
Implementation from standard Java 8 library
final CompletableFuture<Integer> future =
CompletableFuture.supplyAsync(() -> 3 * 2);
// CompletableFuture is functor
future.thenApplyAsync(i -> i * i); // CompletableFuture(36)
future.handleAsync(
(val, exc) -> val != null ? val.toString() : ""
); // CompletableFuture("6")
future.thenAcceptAsync(System.out::println); // out > 6
// CompletableFuture is monad
future.thenComposeAsync(
i -> CompletableFuture.supplyAsync(() -> i * 2)
); // CompletableFuture(12)
Why should I care?Why should I care?
Simple complexity
Composability
Type safety
Unification
Javaz. Functional design in Java 8.

More Related Content

What's hot

Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingJordan Parmer
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Trisha Gee
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 

What's hot (20)

Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 

Similar to Javaz. Functional design in Java 8.

Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazAlexey Remnev
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?Nick Belhomme
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much moreAlin Pandichi
 
How to make the fastest Router in Python
How to make the fastest Router in PythonHow to make the fastest Router in Python
How to make the fastest Router in Pythonkwatch
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveJeff Smith
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8Richard Walker
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015senejug
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJosé Paumard
 

Similar to Javaz. Functional design in Java 8. (20)

Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - Javaz
 
Java8
Java8Java8
Java8
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Lambdas HOL
Lambdas HOLLambdas HOL
Lambdas HOL
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
How to make the fastest Router in Python
How to make the fastest Router in PythonHow to make the fastest Router in Python
How to make the fastest Router in Python
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 

Recently uploaded

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 

Recently uploaded (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 

Javaz. Functional design in Java 8.

  • 2. IntroIntro All Java code can be found at Javaz https://github.com/escalate42/Javaz The emergence of native support for lambdas in Java 8 has opened the possibility to adapt the rich experience of statically typed functional programming languages to the Java world. So the Javaz appears. finally!This presentation can be found at https://slides.com/vadimdubs/javaz​
  • 3. Common functionalCommon functional programming patternsprogramming patterns Functor ApplicativeFunctor Monad First appeared in Haskell programing langugage
  • 4. TypeclassesTypeclasses First appeared in Haskell programing langugage Is a sort of interface that defines some behavior You can think of them kind of as Java interfaces
  • 5.
  • 6. -- Typeclass definition with name Eq, type variable a -- and function == which has two params of type a and -- returns Bool class Eq a where eq :: a -> a -> Bool -- Data Type definition (like Java enum in this case) data TrafficLight = Red | Yellow | Green -- Instance definition for TrafficLight data type and -- Eq typeclass instance Eq TrafficLight where eq Red Red = True eq Yellow Yellow = True eq Green Green = True eq _ _ = False
  • 7. public interface Eq<A> { public boolean eq(A other); } public final class TrafficLight implements Eq<TrafficLight> { public static TrafficLight RED = new TrafficLight(); public static TrafficLight YELLOW = new TrafficLight(); public static TrafficLight GREEN = new TrafficLight(); private TrafficLight() {} @Override public boolean eq(TrafficLight other) { return other == this; } }
  • 8. FunctionFunction @FunctionalInterface interface Function<A, B> { B apply(A a); } Function<A, B> function1 = Functions::function; Function<A, B> function2 = a -> new B(a);
  • 10. @FunctionalInterface interface Function<A, B> { B apply(A a); } Function<A, B> f; Function<B, C> g; static <A, B, C> Function<A, C> compose( Function<A, B> ab, Function<B, C> bc ) { return a -> bc.apply(ab.apply(a)); } Function<A, C> h = compose(f, g);
  • 11. f :: a -> b g :: b -> c . :: (a -> b) -> (b -> c) -> a -> c f1 . f2 = x -> f2 (f1 x) h :: a -> c h = f . g
  • 12. FunctorFunctor for things that can be mapped over. class Functor F where fmap :: (a -> b) -> F a -> F b
  • 13.
  • 14.
  • 15.
  • 16. data Maybe a = Just a | Nothing
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23. FunctorFunctor for things that can be mapped over. class Functor F where fmap :: (a -> b) -> F a -> F b
  • 24. Applicative FunctorApplicative Functor class (Functor F) => Applicative F where pure :: a -> F a (<*>) :: F (a -> b) -> F a -> F b
  • 25.
  • 26.
  • 27.
  • 28.
  • 29. Applicative FunctorApplicative Functor class (Functor F) => Applicative F where pure :: a -> F a (<*>) :: F (a -> b) -> F a -> F b
  • 30. MonadMonad class Monad M where return :: a -> M a (>>=) :: M a -> (a -> M b) -> M b
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37. MonadMonad class Monad M where return :: a -> M a (>>=) :: M a -> (a -> M b) -> M b
  • 38. f :: a -> M a g :: a -> M b -- Bind function (>>=) :: M a -> (a -> M b) -> M b a -> (f a) >>= a -> (g a) -- Same in term of types -- (>>=) is the same as -- composition of functions (a -> M a) >>= (a -> M b) -- Composition of functions (a -> a) . (a -> b)
  • 39.
  • 40. CommonCommon implementationsimplementations Collection - container for a group of values Option/Maybe​ - for optional values Either - for results that either success or failure Future - for async computations
  • 41. OptionOption For optional values, typesafe way to avoid null and null-checks Option<T> always is in one of two states: Some<T> - simple container for value of type T None<T> - represents absence of any value of type T Javaz implementation
  • 42. User auth(String l, String p); Role getRole(User u); Permissions getPermissions(Role r); List<Partner> getPartners(Permissions p); User user = auth("user", "password"); Role role = null; Permissions permissions = null; List<Partner> partners = new ArrayList<>(); if (user != null) { role = getRole(user); } if (role != null) { permissions = getPermissions(role); } if (permissions != null) { partners.addAll(getPartners(permissions)); }
  • 43. Function2<String, String, Option<User>> auth; Function<User, Option<Role>> getRole; Function<Role, Option<Permissions>> getPermissions; Function<Permissions, List<Partner>> getPartners; List<Partner> partners = // trying to authenticate user auth.apply("login", "password") // trying to get Role for this // user from service via http .flatMap(getRole) // the same as >>= // trying to load permissions // from database .flatMap(getPermissions) // trying to load partners from // another data source .map(getPartners) // the same as fmap .getOrElse(new ArrayList());
  • 44. OptionalOptional import static Optional.of; import static Optional.empty; final Optional<Integer> first = of(3); final Optional<Integer> second = of(4); final Optional<Integer> empty = empty(); // Optional is a functor and monad first.map(i -> i * i) // Some(9) empty.map(i -> i * i) // None first.flatMap(f -> second.map(s -> f + s)); // Some(7) first.flatMap(f -> empty.map(s -> f + s)); // None Implementation from standard Java 8 library
  • 45. EitherEither For results that either success or failure, typesafe way to avoid usege of exceptions. Has no analogs in standard Java library. Either<L, R> always is in one of two states: Right<L, R> - container for value of type R Left<L, R> - container for values of type L that represents some failure Javaz implementation
  • 46. F2<String, String, Either<ErrorInfo, User>> auth; F<User, Either<ErrorInfo, Role>> getRole; F<Role, Either<ErrorInfo, Permissions>> getPermissions; F<Permissions, List<Partner>> getPartners; Either<ErrorInfo, List<Partner>> eitherPartners = // trying to authenticate user auth.apply("login", "password") // trying to get Role for this // user from service via http .fmap(getRole) // trying to load permissions // from database .fmap(getPermissions) // trying to load partners from // another data source .map(getPartners); eitherPartners.mapLeft(logger::error); List<String> partnerNames = eitherPartners.foldRight( new ArrayList(), partner -> partner.getName )
  • 47. StreamStream final Stream<Integer> stream = Arrays.asList(1, 2, 3, 4, 5).stream(); // Streams are functors stream.map(i -> i + 1); // [2, 3, 4, 5, 6] stream.forEach(System.out::print); // out > 12345 Implementation from standard Java 8 library
  • 48. StreamStream final Stream<Integer> stream = Arrays.asList(1, 2, 3, 4, 5).stream(); // Streams are monads stream.flatMap( i -> Arrays.asList(i + 1, i + 2).stream() ); // [2, 3, 3, 4, 4, 5, 5, 6, 6, 7] Implementation from standard Java 8 library
  • 49. StreamStream Function<User, Stream<Permission>> permissionsByUser; Function<Permission, Stream<Partner>> partnersByPermissions; Stream<User> users = Arrays.asList(user1, user2).stream(); Set<Partners> availablePartners = users .flatMap(permissionByUser) // get all permissions of user 1 and user2 .distinct() // left only unique items .flatMap(partnersByPermissions) // get all partners available through permissions .collect(Collectors.toSet); Implementation from standard Java 8 library
  • 50. FutureFuture Javaz implementation Function2<String, String, Future<User>> auth; Function<User, Future<Stream<User>>> getFriends; Function<User, Stream<Group>> getGroups; Future<User> user = auth.apply("login", "password"); Future<Stream<Group>> myGroups = user.map(getGroups) Future<Stream<User>> friendsGroups = user .flatMap(getFriends) .map(Stream::flatMap(getGroups).distinct()); Future<Set<Group>> uniqueFriendsGroups = yieldFor( myGroups, myFirends, (myGroups, firendsGroups) -> friendsGroups.collect(toSet) .removeAll(myGroups.collect(toSet)) ) uniqueFriendsGroups.get(100, TimeUnit.MILLISECONDS)
  • 51. CompletableFutureCompletableFuture Implementation from standard Java 8 library final CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 3 * 2); // CompletableFuture is functor future.thenApplyAsync(i -> i * i); // CompletableFuture(36) future.handleAsync( (val, exc) -> val != null ? val.toString() : "" ); // CompletableFuture("6") future.thenAcceptAsync(System.out::println); // out > 6 // CompletableFuture is monad future.thenComposeAsync( i -> CompletableFuture.supplyAsync(() -> i * 2) ); // CompletableFuture(12)
  • 52. Why should I care?Why should I care? Simple complexity Composability Type safety Unification