SlideShare a Scribd company logo
aftermath of functional
programming
the good parts
@ggalmazor
@buntplanet
disclaimer
functional
programming
object orientation
“FP != OO”
mutation
why bother
equality rules
Stuff a = new Stuff();
Stuff b = a.changeSomething();
if (a.equals(b))
System.out.println("WTF");
output args
Stuff a = new Stuff();
// a.something holds 42
doStuffWith(a);
// a.something holds 33
// WTF
entity != value
surprises
a.setSuch();
a.setWow();
a.setVery();
a.setCoupling();
concurrency
control
how to avoid it
change your design
isolate mutation
copy on write
tips
ValueObject
class Stuff {
private final Integer aNumber;
private final String aString;
Stuff(Integer aNumber, String aString) {
this.aNumber = aNumber;
this.aString = aString;
}
…
}
class Stuff {
…
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Stuff stuff = (Stuff) o;
return Objects.equals(aNumber,
stuff.aNumber) &&
Objects.equals(aString,
stuff.aString);
}
…
}
ValueObject
ValueObject
class Stuff {
…
@Override
public int hashCode() {
return Objects.hash(aNumber, aString);
}
…
}
factories
functional data
structures
side effects
why bother
accidental complexity
coupling
cqrs
object serialization in a
distributed context
final AtomicInteger counter =
new AtomicInteger(0);
rdd.map(stuff -> {
int i = counter();
return OtheStuff(i, stuff);
});
tips
think in pure functions
isolate and identify
side effects
functional data
structures
tools
option
nulls
monad
antipatterns
Optional.ofNullable(maybeNull).get();
antipatterns
Optional<Object> o =
Optional.ofNullable(maybeNull);
if (o.isPresent())
doStuffWith(o.get());
antipatrones
Optional<List<Object>> foo
antipatrones
Map<String,Optional<Object>> foo
tips
tuple
design exploration
tips
try
exceptions
when i use try
when i use try
Try.of(someComputation)
Try.of(someComputation)
.onFailure(logger::error)
.get()
when i use try
when i use try
Try.of(someComputation)
.flatMap(someOtherComputation)
.onFailure(logger::error)
.get()
when i use try
Try.run(someVoidComputation)
.anThen(someVoidComputation)
.onFailure(logger::error)
.get()
when i use try
Try.of(someComputation)
.orElse(42)
antipatterns
antipatterns
Try.run(()-> {
int a = somethingOverHere();
int b = somethingOverThere(a);
doTheGangnamStyle(a,b);
}).onFailure(t-> {
logger.error(“Everything’s f*cked!!!”, t);
}).get();
antipatterns
Try.of(thisWillReturnNull).toOption()
antipatrones
Try.of(someVoidComputation)
.map(thisWillGetDirty)
functional data
structures
why bother
know your tools
filter, map, fold
impact in your design
tips
small blocks
don’t go crazy
really. don’t go crazy
types
thanks!

More Related Content

PDF
Guava Overview. Part 1 @ Bucharest JUG #1
PDF
Replace OutputIterator and Extend Range
PDF
Java Script Workshop
PDF
Short intro to ECMAScript
PPT
Chapter1 intro toprincipleofc#_datastructure_b_cs
PDF
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
PPT
Chapter 7: Queue data structure
PDF
Beauty and the beast - Haskell on JVM
Guava Overview. Part 1 @ Bucharest JUG #1
Replace OutputIterator and Extend Range
Java Script Workshop
Short intro to ECMAScript
Chapter1 intro toprincipleofc#_datastructure_b_cs
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
Chapter 7: Queue data structure
Beauty and the beast - Haskell on JVM

What's hot (15)

PPTX
Introduction to Javascript
PPT
computer notes - Data Structures - 9
PPT
Chapter 3: basic sorting algorithms data structure
PPT
Unit iii
PPTX
4front en
PPTX
Managing Input Output Operations
PPT
Chapter 4: basic search algorithms data structure
PPT
Chapter 5: linked list data structure
DOCX
Problemas secuenciales.
PDF
Introduction to programming with ZIO functional effects
PPTX
Object oriented analysis and design flexible software
DOCX
DOCX
Estructura secuencial -garcia
PPTX
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
PPTX
Introduction to Javascript
computer notes - Data Structures - 9
Chapter 3: basic sorting algorithms data structure
Unit iii
4front en
Managing Input Output Operations
Chapter 4: basic search algorithms data structure
Chapter 5: linked list data structure
Problemas secuenciales.
Introduction to programming with ZIO functional effects
Object oriented analysis and design flexible software
Estructura secuencial -garcia
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
Ad

Viewers also liked (8)

PDF
Control de Versiones - Slides
PDF
Aftermath of functional programming. The good parts
PPT
Comité paritario de salud ocupacional
PDF
Salud trabajo autocuidado
PPTX
Autocuidado
PDF
Hype vs. Reality: The AI Explainer
PDF
Study: The Future of VR, AR and Self-Driving Cars
Control de Versiones - Slides
Aftermath of functional programming. The good parts
Comité paritario de salud ocupacional
Salud trabajo autocuidado
Autocuidado
Hype vs. Reality: The AI Explainer
Study: The Future of VR, AR and Self-Driving Cars
Ad

Similar to Aftermath of functional programming. the good parts (20)

PDF
JEEConf 2017 - Having fun with Javassist
PDF
Scala in practice
PPTX
Chap2 class,objects contd
PPT
Paradigmas de Linguagens de Programacao - Aula #4
ODP
Machine-level Composition of Modularized Crosscutting Concerns
PPTX
EcmaScript unchained
ODP
Ast transformations
PPTX
Java 8 Puzzlers [as presented at OSCON 2016]
PPTX
Core java
PPT
2012 JDays Bad Tests Good Tests
PPT
Tips and Tricks of Developing .NET Application
PPTX
Using Reflections and Automatic Code Generation
PDF
JavaOne 2015 - Having fun with Javassist
PDF
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake
PDF
TypeScript Introduction
PPT
Operators
PPTX
A topology of memory leaks on the JVM
PPT
Java operators
PPSX
Java.lang.object
PPTX
05 pig user defined functions (udfs)
JEEConf 2017 - Having fun with Javassist
Scala in practice
Chap2 class,objects contd
Paradigmas de Linguagens de Programacao - Aula #4
Machine-level Composition of Modularized Crosscutting Concerns
EcmaScript unchained
Ast transformations
Java 8 Puzzlers [as presented at OSCON 2016]
Core java
2012 JDays Bad Tests Good Tests
Tips and Tricks of Developing .NET Application
Using Reflections and Automatic Code Generation
JavaOne 2015 - Having fun with Javassist
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake
TypeScript Introduction
Operators
A topology of memory leaks on the JVM
Java operators
Java.lang.object
05 pig user defined functions (udfs)

Recently uploaded (20)

PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Cost to Outsource Software Development in 2025
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Designing Intelligence for the Shop Floor.pdf
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Digital Strategies for Manufacturing Companies
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
assetexplorer- product-overview - presentation
PPTX
Transform Your Business with a Software ERP System
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
CHAPTER 2 - PM Management and IT Context
Cost to Outsource Software Development in 2025
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Computer Software and OS of computer science of grade 11.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Designing Intelligence for the Shop Floor.pdf
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Odoo POS Development Services by CandidRoot Solutions
How to Choose the Right IT Partner for Your Business in Malaysia
Softaken Excel to vCard Converter Software.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
Design an Analysis of Algorithms I-SECS-1021-03
Digital Strategies for Manufacturing Companies
L1 - Introduction to python Backend.pptx
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
assetexplorer- product-overview - presentation
Transform Your Business with a Software ERP System
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...

Aftermath of functional programming. the good parts

Editor's Notes

  • #2: This is talk is about what remains after more than one year of learning about Functional Programming, Category Theory, Lambda Calculus, Javaslang and some Haskell and Scala too. I work with Apache Spark in Java8 & Javaslang. It’s a distributed computation context that works with large quantities of data. I started my journey into Functional Programming to reduce the complexity of my code.
  • #4: Functional Programming “[…] treats computation as the evaluation of mathematical functions […]”: - Avoid changing state and mutable data - Use expressions or declarations instead of statements - Elimination of side effects (source: https://www.wikiwand.com/en/Functional_programming)
  • #5: Alan Kay’s definition of Object Orientation: - Messaging - Local retention, protection and hiding of state-process - Extreme late binding of all things (source: http://c2.com/cgi/wiki?AlanKaysDefinitionOfObjectOriented)
  • #6: This statement doesn’t make sense. Can you do OO without expressions, immutability or only by having side-effects? Can you do FP without messaging, encapsulation or late binding? Maybe you can but I bet that the result won’t be very satisfying.
  • #9: This example shows a block that is counter-intuitive and hard to follow because we need to inspect Stuff.changeSomething() to understand what’s going on. You expect that applying a change in something makes that something different, not the same.
  • #10: Calling a void method with something should not change it. You expect a side effect, not an object mutation. Immutability here helps us to explicitly identify this kind of behavior, reducing the cost of understanding what’s going on.
  • #11: An entity’s equality is based on some kind of identifying property. A value’s equality is based on its content.
  • #12: Can you rearrange this statements? You need to peek inside to decide.
  • #13: No need for sharing memory space between threads. No locks, no concurrency control. Easier (safer) serialization of objects between processes.
  • #14: The same way that new Integer(“a”) doesn’t compile or will throw some kind of error in run time, a value shouldn’t be instantiated if its contents are not valid. All instances of values are inherently valid and that lets us to make some useful assumptions about data in our code.
  • #16: If you can’t get an object in one pass, that is speaking about your design.
  • #17: Use mutation locally inside a method, but return something immutable. Use Builder Pattern for constructing complex objects and isolate mutation inside them.
  • #18: You can make a shallow copy or a deep copy. Both options have tradeoffs that you’ll have to reason about.
  • #20: All properties are final and can only be set in the constructor.
  • #21: Equality is based on the contents of a value.
  • #22: The hash of a value is the hash of its contents.
  • #23: Hide object creation complexity inside factory methods. You can make the constructor private as well.
  • #24: This will apply for everything else in this talk. More to come about this.
  • #27: When going on mutation we’ve already talked about the impact that unexpected or implicit behavior has in the cost of understanding a piece of code. Side effects prevent referential transparency and that’s a feature that makes easier changing your design.
  • #28: Sometimes coupling can be good. It’s always a tradeoff between flexibility vs coherence.
  • #29: Making a question should not change the answer. Formally, a method should return a value only if it is referentially transparent and, therefore, lacking of side effects.
  • #30: After merging partial results from Executor threads, the value of i will be unpredictable.
  • #32: They come with perks: combination, memoization, laziness… If you use good names, you will improve your code’s expressiveness.
  • #33: Use void functions for side effects. Do you have an IO Monad in your language?
  • #37: What’s the meaning of null in your code? Can you define it? Where do nulls come from? How do you model the absence of something? We can force policies about this problem in Context Boundaries.
  • #38: Avoid NullPointerExceptions
  • #39: Just use maybeNull.
  • #40: Use Optional as a monad to avoid that if block. This is just the same as null-checking without Options.
  • #41: An Option is a List<Object> with a cardinality of 0 or 1. You can use an empty List instead.
  • #42: Same principle here. Use a Map<String,Object> and don’t put keys that hold nothing.
  • #43: Use Option to describe explicitly that there are properties in an object that might not be present. Hide their creation inside factory methods (don’t force your users to use Option). Try to limit how far an Option will propagate after it’s creation. Obtain a value, use a default or throw as soon as you can. A model should be able to take these decisions about its state.
  • #45: We start working with primitive values, then types and functions. This defines our design. You can use Tuples as a scaffolding when exploring your solution. Only after knowing all aspects of the problem you’re trying to solve, then you will produce a good design. A complex design with lots of abstractions is harder to refactor. Refactoring some tuples is easier than refactoring a cluster of classes. The resulting combination of tuples and functions that return or accept tuples can become classes.
  • #46: Never forget to “solidify” your tuples into a type. Don’t return nor accept tuples in your public methods (don’t force your users to use Tuples).
  • #48: Checked vs unchecked. Ignored vs caught. Recovered with some value vs propagated.
  • #50: When I want to completely ignore an exception.
  • #51: Syntactic sugar. This being an expression is also nicer.
  • #52: When I need to perform computations that are data-dependent in a chain of calls. First call’s output is second’s call input, and so on.
  • #53: Also with void functions, to define a sequence of calls that might throw.
  • #54: To get a default when something fails.
  • #56: If you’re not using Try as a monad or you’re not extracting those anonymous functions and giving them names, you’re just fine with a classic try-catch block. This is harder to follow and understand and imposes limitations that will get in your way.
  • #57: This results in a Some<Object> holding a null. A Try is not an Option. The Success state of a Try corresponds to the Success state of an Option, with is Some, not None, even if its value will be null.
  • #58: Mapping a void function forces you to deal with Void type in Java. Tends to make a mess.
  • #59: Immutable, persistent and all methods are referentially transparent.
  • #61: Take a look how your collection implementations works in your language. Do they really suit your needs? The best structure to iterate over a collection of data is a Linked List most of the times. In Java we abuse of ArrayList and it’s clearly not the best option for this.
  • #62: Your swiss army knife.
  • #63: Working with collections in a functional style lets us use functions with names. We can think about what we need to do without worrying about how it’s going to be executed.
  • #65: Take into account the laziness of the collections you’re using. Maybe you can divide a big map into four small maps without an efficiency penalty. If your collection is not lazy, you can always combine those mapping functions yourself to avoid iterating over data more than once.
  • #66: Fold and reduce are hard to master in the beginning can be counter-intuitive. Don’t try to solve everything with a fold. What if I tell you that every operation in a collection can be (and often is) expressed based on folds? WHAT?!
  • #67: You can start by using traditional for blocks or forEach() for your aggregations and the train yourself improving them into a fold. Compare your results and maintain what feels more simple.
  • #68: Functional Programming is not only about functions. It’s also about types. Type theory concepts in mathematics are older (1910s) than functional programming. Lambda Calculus was proposed in 1940 with and without types from the beginning. Types have deep roots in programming theory. Having a rich and honest type system improves deeply the expressiveness of your code.