SlideShare a Scribd company logo
1 of 46
La Programmation
Fonctionnelle
A quick view
Pourquoi y’a-t-il plusieurs façons de
programmer?
C’est une bonne question!
2 écoles
https://interstices.info/alan-turing-du-calculable-a-lindecidable/
Caractéristiques
Functions are First Class citizens
○ The ability to treat functions as values
○ The ability to pass those values into other functions
○ Being able to write small snippets of code as anonymous functions
○ Not having to create deep hierarchies of classes (that sometimes feel “artifical”)
○ Most FP languages are “low ceremony” languages, meaning that they require less
boilerplate code than other languages
C’est quoi une fonction?
C’est quoi une fonction?
https://www.codingame.com/playgrounds/2980/practical-introduction-to-functional-
programming-with-js/pure-functions
Pure functions are easier to reason about
First, pure functions are easier to reason about because you know that they can’t do certain things, such as talk to the
outside world, have hidden inputs, or modify hidden state. Because of this, you’re guaranteed that their function signatures
tell you (a) exactly what’s going into each function, and (b) coming out of each function.
In his book, Clean Code (affiliate link), Robert Martin writes:
“The ratio of time spent reading (code) versus writing is well over 10 to 1 ... (therefore) making it
easy to read makes it easier to write.”
I suspect that this ratio is lower with FP. Because pure functions are easier to reason about:
● I spend less time “reading” them.
● I can keep fewer details in my brain for every function that I read.
This is what functional programmers refer to as “a higher level of abstraction.”
Dishonest function (1)
function x() { … }
que fait - elle ?
https://enterprisecraftsmanship.com/posts/what-is-functional-programming/
Dishonest function (2): referentially
transparent.
A referentially transparent function always produces the same result as long as you supply it the same
arguments. It means that such function should operate only the values we pass in, it shouldn’t refer to the global
state.
Here’s an example:
public long TicksElapsedFrom(int year)
{
DateTime now = DateTime.Now;
DateTime then = new DateTime(year, 1, 1);
return (now - then).Ticks;
}
Dishonest function (2): referentially
transparent.
public long TicksElapsedFrom(int year)
{
DateTime now = DateTime.Now;
DateTime then = new DateTime(year, 1, 1);
return (now - then).Ticks;
}
This method is not referentially transparent because it returns different results even if we pass it the
same year. The reason here is that it refers to the global DatetTime.Now property.
Dishonest function (2): referentially
transparent.
A referentially transparent alternative for this method would be:
public long TicksElapsedFrom(int year, DateTime now)
{
DateTime then = new DateTime(year, 1, 1);
return (now - then).Ticks;
}
Dishonest function (3): method signature
honesty.
public int Divide(int x, int y)
{
return x / y;
}
The Divide method, despite being referentially transparent, is not a mathematical function. Its signature
states that it accepts any two integers and returns another integer. But what happens if we pass it 1 and
0 as input parameters?
Dishonest function (3): method signature
honesty.
public int Divide(int x, int y)
{
return x / y;
}
S
SOLUTION ???
Dishonest function (3): method signature
honesty.
public static int Divide(int x, NonZeroInteger y)
{
return x / y.Value;
}
Dishonest function (3): method signature
honesty.
public static int ? Divide(int x, int y)
{
if (y == 0)
return null;
return x / y;
}
This version is also honest as it now doesn’t guarantee that it will return an integer for any possible
combination of input values.
Dishonest function (4): exceptions
Exceptions
Exceptions is another source of dishonesty for your code base. Methods that employ exceptions to
control the program flow are not mathematical functions because, just like side effects, exceptions hide
the actual outcome of the operation the method performs.
Moreover, exceptions have a goto semantics meaning that they allow you to easily jump from any point
of your program to a catch block. In fact, exceptions perform even worse because the goto statement
doesn’t allow for jumping outside a particular method, whereas with exceptions you can cross multiple
layers in your code base with ease.
Dishonest function (4): exceptions
Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have
exceptions when you try to access servers that are down or files that are missing, so what can you do?
Option/Some/None
Try/Success/Failure
def toInt(s: String): Option[Int] = {
try {
Some(Integer.parseInt(s.trim))
} catch {
case e: Exception => None
}
def toInt(s: String): Try[Int] = Try {
Integer.parseInt(s.trim)
}
toInt(x) match {
case Success(i) => println(i)
case Failure(s) => println(s"Failed. Reason: $s")
}
Dishonest function (5): effets de bord
Dishonest function (5): effets de bord
The first such practice is avoiding side effects as much as possible by employing immutability all over your code base. This
technique is important because the act of mutating state contradicts the functional principles.
The signature of a method with a side effect doesn’t communicate enough information about what the actual result of the
operation is, and that hinders our ability to reason about it. In order to validate your assumptions regarding the code you
are writing, not only do you have to look at the method’s signature itself, but you also need to fall down to its
implementation details and see if this method leaves any side effects that you didn’t expect.
Dishonest function (5): effets de bord
Overall, code with data structures that change over time is harder to debug and is more error-prone. It brings even more
problems in multi-threaded applications where you can have all sorts of nasty race conditions.
When you operate immutable data only, you force yourself to reveal hidden side effects by stating them in the method’s
signature and thus making it honest. This makes the code more readable because you don’t have to fall down to the
methods' implementation details in order to reason about the program flow. With immutable classes, you can just look at
the signature of a method and get a good understanding of what is going on right away, without too much effort.
Avoid nulls
Another practice in this list is avoiding nulls. It turns out that the use of nulls makes your code dishonest
as the signature of the methods using them doesn’t tell all information about the possible outcome the
corresponding operation may have.
Testing is easier, and pure functions lend
themselves well to techniques like property-
based testing
https://alvinalexander.com/scala/fp-book/benefits-of-functional-programming/#testing-is-easier-and-pure-
functions-lend-themselves-well-to-techniques-like-property-based-testing
https://enterprisecraftsmanship.com/posts/immutable-architecture/
Quelles différences?
On the scale of abstraction, the Turing Machine sits at one end, where Lambda
Calculus sits at the other.
Two extremes, yet with lots in common:
there is no problem one can solve that the other one cannot.
https://www.eonics.nl/story/functional-programming-part-1-historical-context/
Avantages
1. Pure functions are easier to reason about
2. Testing is easier, and pure functions lend themselves well to techniques like property-
based testing
3. Debugging is easier
4. Programs are more bulletproof
5. Programs are written at a higher level, and are therefore easier to comprehend
6. Function signatures are more meaningful
7. Parallel/concurrent programming is easier
Take away
● Paramètres de fonction plutôt que données globales (même de classe)
● Créer des objets plutôt que de les modifier (immutable)
● Option plutôt que ‘null’
● Option / Try / Either / Result ... (monads) plutôt qu’une exception
● Collection API / récursivité plutôt que boucles for/while
● Eviter les ‘if’ autant que possible
● Séparation technique / métier
● Functionnal core / Imperative shell
https://www.slideshare.net/loicknuchel/comprendre-la-programmation-fonctionnelle-blend-web-mix-le-02112016/60
https://www.youtube.com/watch?v=
Y7StjYhXvpE
MERCI
contact@primobox.com
www.primobox.com

More Related Content

Similar to Vendredi Tech_ la programmation fonctionnelle.pptx

Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
olracoatalub
 
Mark asoi ppt
Mark asoi pptMark asoi ppt
Mark asoi ppt
mark-asoi
 

Similar to Vendredi Tech_ la programmation fonctionnelle.pptx (20)

Mca 2 sem u-1 iintroduction
Mca 2 sem u-1 iintroductionMca 2 sem u-1 iintroduction
Mca 2 sem u-1 iintroduction
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
 
Functional Effects - Part 1
Functional Effects - Part 1Functional Effects - Part 1
Functional Effects - Part 1
 
The Rest of the Best
The Rest of the BestThe Rest of the Best
The Rest of the Best
 
Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
Object Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsObject Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of Exams
 
Mark asoi ppt
Mark asoi pptMark asoi ppt
Mark asoi ppt
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Reliability Patterns for Distributed Applications
Reliability Patterns for Distributed ApplicationsReliability Patterns for Distributed Applications
Reliability Patterns for Distributed Applications
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
Making an Exception
Making an ExceptionMaking an Exception
Making an Exception
 
Book management system
Book management systemBook management system
Book management system
 
My final requirement
My final requirementMy final requirement
My final requirement
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Intro To AOP
Intro To AOPIntro To AOP
Intro To AOP
 

More from Guillaume Saint Etienne

Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...
Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...
Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...
Guillaume Saint Etienne
 
Electronic Music and Software Craftsmanship: analogue patterns.
Electronic Music and Software Craftsmanship: analogue patterns.Electronic Music and Software Craftsmanship: analogue patterns.
Electronic Music and Software Craftsmanship: analogue patterns.
Guillaume Saint Etienne
 

More from Guillaume Saint Etienne (20)

Ecologie du Logiciel (Craft Luxembourg 2022).pdf
Ecologie du Logiciel (Craft Luxembourg 2022).pdfEcologie du Logiciel (Craft Luxembourg 2022).pdf
Ecologie du Logiciel (Craft Luxembourg 2022).pdf
 
musique electronique au cinéma.pptx
musique electronique au cinéma.pptxmusique electronique au cinéma.pptx
musique electronique au cinéma.pptx
 
DDD FOR POs.pdf
DDD FOR POs.pdfDDD FOR POs.pdf
DDD FOR POs.pdf
 
Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...
Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...
Tout ce que vous avez voulu savoir sur les Doublures sans jamais oser le dema...
 
des algoritmes et des hommes (ethique et code).pdf
des algoritmes et des hommes (ethique et code).pdfdes algoritmes et des hommes (ethique et code).pdf
des algoritmes et des hommes (ethique et code).pdf
 
La crise Agile chez les Developpeurs (AGrenoble2019) (1).pdf
La crise Agile chez les Developpeurs (AGrenoble2019) (1).pdfLa crise Agile chez les Developpeurs (AGrenoble2019) (1).pdf
La crise Agile chez les Developpeurs (AGrenoble2019) (1).pdf
 
How we can BUILD.pdf
How we can BUILD.pdfHow we can BUILD.pdf
How we can BUILD.pdf
 
des mutants dans le code.pdf
des mutants dans le code.pdfdes mutants dans le code.pdf
des mutants dans le code.pdf
 
_(V3.0) Aux sources de la simplicité Bordeaux 2022.pptx
_(V3.0) Aux sources de la simplicité Bordeaux 2022.pptx_(V3.0) Aux sources de la simplicité Bordeaux 2022.pptx
_(V3.0) Aux sources de la simplicité Bordeaux 2022.pptx
 
Il n’y a pas de bons développeurs.pptx
Il n’y a pas de bons développeurs.pptxIl n’y a pas de bons développeurs.pptx
Il n’y a pas de bons développeurs.pptx
 
Living Documentation (TDD, BDD).pptx
Living Documentation (TDD, BDD).pptxLiving Documentation (TDD, BDD).pptx
Living Documentation (TDD, BDD).pptx
 
Agile pour l'echafaud ATT2020.pptx
Agile pour l'echafaud ATT2020.pptxAgile pour l'echafaud ATT2020.pptx
Agile pour l'echafaud ATT2020.pptx
 
10 ans de Code (Agile Bordeaux 2019).pptx
10 ans de Code (Agile Bordeaux 2019).pptx10 ans de Code (Agile Bordeaux 2019).pptx
10 ans de Code (Agile Bordeaux 2019).pptx
 
Feedback on DDD Europe - short -event storming.pptx
Feedback on DDD Europe - short -event storming.pptxFeedback on DDD Europe - short -event storming.pptx
Feedback on DDD Europe - short -event storming.pptx
 
Crise agile chez les développeurs (frug agile 2020)
Crise agile chez les développeurs (frug agile 2020)Crise agile chez les développeurs (frug agile 2020)
Crise agile chez les développeurs (frug agile 2020)
 
My feedback on ddd europe
My feedback on ddd europeMy feedback on ddd europe
My feedback on ddd europe
 
Electronic Music and Software Craftsmanship: analogue patterns.
Electronic Music and Software Craftsmanship: analogue patterns.Electronic Music and Software Craftsmanship: analogue patterns.
Electronic Music and Software Craftsmanship: analogue patterns.
 
Tdd vs SQL
Tdd vs SQLTdd vs SQL
Tdd vs SQL
 
Clean architectures
Clean architecturesClean architectures
Clean architectures
 
Services & Contrats Agiles
Services & Contrats AgilesServices & Contrats Agiles
Services & Contrats Agiles
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Vendredi Tech_ la programmation fonctionnelle.pptx

  • 2. Pourquoi y’a-t-il plusieurs façons de programmer? C’est une bonne question!
  • 4.
  • 5.
  • 6.
  • 7.
  • 9.
  • 10. Functions are First Class citizens ○ The ability to treat functions as values ○ The ability to pass those values into other functions ○ Being able to write small snippets of code as anonymous functions ○ Not having to create deep hierarchies of classes (that sometimes feel “artifical”) ○ Most FP languages are “low ceremony” languages, meaning that they require less boilerplate code than other languages
  • 11. C’est quoi une fonction?
  • 12. C’est quoi une fonction?
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 19. Pure functions are easier to reason about First, pure functions are easier to reason about because you know that they can’t do certain things, such as talk to the outside world, have hidden inputs, or modify hidden state. Because of this, you’re guaranteed that their function signatures tell you (a) exactly what’s going into each function, and (b) coming out of each function. In his book, Clean Code (affiliate link), Robert Martin writes: “The ratio of time spent reading (code) versus writing is well over 10 to 1 ... (therefore) making it easy to read makes it easier to write.” I suspect that this ratio is lower with FP. Because pure functions are easier to reason about: ● I spend less time “reading” them. ● I can keep fewer details in my brain for every function that I read. This is what functional programmers refer to as “a higher level of abstraction.”
  • 20. Dishonest function (1) function x() { … } que fait - elle ? https://enterprisecraftsmanship.com/posts/what-is-functional-programming/
  • 21. Dishonest function (2): referentially transparent. A referentially transparent function always produces the same result as long as you supply it the same arguments. It means that such function should operate only the values we pass in, it shouldn’t refer to the global state. Here’s an example: public long TicksElapsedFrom(int year) { DateTime now = DateTime.Now; DateTime then = new DateTime(year, 1, 1); return (now - then).Ticks; }
  • 22. Dishonest function (2): referentially transparent. public long TicksElapsedFrom(int year) { DateTime now = DateTime.Now; DateTime then = new DateTime(year, 1, 1); return (now - then).Ticks; } This method is not referentially transparent because it returns different results even if we pass it the same year. The reason here is that it refers to the global DatetTime.Now property.
  • 23. Dishonest function (2): referentially transparent. A referentially transparent alternative for this method would be: public long TicksElapsedFrom(int year, DateTime now) { DateTime then = new DateTime(year, 1, 1); return (now - then).Ticks; }
  • 24. Dishonest function (3): method signature honesty. public int Divide(int x, int y) { return x / y; } The Divide method, despite being referentially transparent, is not a mathematical function. Its signature states that it accepts any two integers and returns another integer. But what happens if we pass it 1 and 0 as input parameters?
  • 25. Dishonest function (3): method signature honesty. public int Divide(int x, int y) { return x / y; } S SOLUTION ???
  • 26. Dishonest function (3): method signature honesty. public static int Divide(int x, NonZeroInteger y) { return x / y.Value; }
  • 27. Dishonest function (3): method signature honesty. public static int ? Divide(int x, int y) { if (y == 0) return null; return x / y; } This version is also honest as it now doesn’t guarantee that it will return an integer for any possible combination of input values.
  • 28. Dishonest function (4): exceptions Exceptions Exceptions is another source of dishonesty for your code base. Methods that employ exceptions to control the program flow are not mathematical functions because, just like side effects, exceptions hide the actual outcome of the operation the method performs. Moreover, exceptions have a goto semantics meaning that they allow you to easily jump from any point of your program to a catch block. In fact, exceptions perform even worse because the goto statement doesn’t allow for jumping outside a particular method, whereas with exceptions you can cross multiple layers in your code base with ease.
  • 29. Dishonest function (4): exceptions Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? Option/Some/None Try/Success/Failure def toInt(s: String): Option[Int] = { try { Some(Integer.parseInt(s.trim)) } catch { case e: Exception => None } def toInt(s: String): Try[Int] = Try { Integer.parseInt(s.trim) } toInt(x) match { case Success(i) => println(i) case Failure(s) => println(s"Failed. Reason: $s") }
  • 30. Dishonest function (5): effets de bord
  • 31. Dishonest function (5): effets de bord The first such practice is avoiding side effects as much as possible by employing immutability all over your code base. This technique is important because the act of mutating state contradicts the functional principles. The signature of a method with a side effect doesn’t communicate enough information about what the actual result of the operation is, and that hinders our ability to reason about it. In order to validate your assumptions regarding the code you are writing, not only do you have to look at the method’s signature itself, but you also need to fall down to its implementation details and see if this method leaves any side effects that you didn’t expect.
  • 32. Dishonest function (5): effets de bord Overall, code with data structures that change over time is harder to debug and is more error-prone. It brings even more problems in multi-threaded applications where you can have all sorts of nasty race conditions. When you operate immutable data only, you force yourself to reveal hidden side effects by stating them in the method’s signature and thus making it honest. This makes the code more readable because you don’t have to fall down to the methods' implementation details in order to reason about the program flow. With immutable classes, you can just look at the signature of a method and get a good understanding of what is going on right away, without too much effort.
  • 33. Avoid nulls Another practice in this list is avoiding nulls. It turns out that the use of nulls makes your code dishonest as the signature of the methods using them doesn’t tell all information about the possible outcome the corresponding operation may have.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38. Testing is easier, and pure functions lend themselves well to techniques like property- based testing https://alvinalexander.com/scala/fp-book/benefits-of-functional-programming/#testing-is-easier-and-pure- functions-lend-themselves-well-to-techniques-like-property-based-testing
  • 39.
  • 40.
  • 42. Quelles différences? On the scale of abstraction, the Turing Machine sits at one end, where Lambda Calculus sits at the other. Two extremes, yet with lots in common: there is no problem one can solve that the other one cannot. https://www.eonics.nl/story/functional-programming-part-1-historical-context/
  • 43. Avantages 1. Pure functions are easier to reason about 2. Testing is easier, and pure functions lend themselves well to techniques like property- based testing 3. Debugging is easier 4. Programs are more bulletproof 5. Programs are written at a higher level, and are therefore easier to comprehend 6. Function signatures are more meaningful 7. Parallel/concurrent programming is easier
  • 44. Take away ● Paramètres de fonction plutôt que données globales (même de classe) ● Créer des objets plutôt que de les modifier (immutable) ● Option plutôt que ‘null’ ● Option / Try / Either / Result ... (monads) plutôt qu’une exception ● Collection API / récursivité plutôt que boucles for/while ● Eviter les ‘if’ autant que possible ● Séparation technique / métier ● Functionnal core / Imperative shell https://www.slideshare.net/loicknuchel/comprendre-la-programmation-fonctionnelle-blend-web-mix-le-02112016/60