SlideShare a Scribd company logo
1 of 52
Functional Programming in C#
What is Functional Programming?
• Side-effect free programming?
• Higher order functions?
• Use of a functional language like F# / Haskell / Scala?
Functional programming is
programming with mathematical
functions.
Problem solved!
What is Functional Programming?
Mathematical
function
Class
method=
What is Functional Programming?
f
Referential transparency:
same input – same result
Information about possible
inputs and outcomes
What is Functional Programming?
public double Calculate(double x, double y)
{
return x * x + y * y;
}
public long TicksElapsedFrom(int year)
{
DateTime now = DateTime.Now;
DateTime then = new DateTime(year, 1, 1);
return (now - then).Ticks;
}
Same input – same result Result is always different
What is Functional Programming?
public static int Divide(int x, int y)
{
return x / y;
}
f
Integer
Integer
Integer
1
0
?
DivideByZeroException
Method Signature Honesty
Method
signature
All possible
inputs
All possible
outcomes
Method Signature Honesty
Honest signatureDishonest signature
public static int Divide(int x, int y)
{
return x / y;
}
public static int Divide(int x, NonZeroInteger y)
{
return x / y.Value;
}
public static int? Divide(int x, int y)
{
if (y == 0)
return null;
return x / y;
}
Mathematical Function
• Honest
• Has precisely defined input and output
• Referentially transparent
• Doesn’t affect or refer to the global state
Why Functional Programming?
Composable
Easy to reason about
Easier to unit test
Reducing
complexity
Immutability
• Immutability
• Inability to change data
• State
• Data that changes over time
• Side effect
• A change that is made to some state
Immutability
Mutable
operations
Dishonest
code=
Immutability
fInput Output
Side effect
Method
signature
Hidden part
Immutability
fInput
Output
Side effect
Method
signature
Hidden part
Output 2
Why Does Immutability Matter?
• Increased readability
• A single place for validating invariants
• Automatic thread safety
How to Deal with Side Effects
Command–query separation principle
Command Query
Produces side effects Side-effect free
Returns void Returns non-void
How to Deal with Side Effects
public class CustomerService {
public void Process(string customerName, string addressString) {
Address address = CreateAddress(addressString);
Customer customer = CreateCustomer(customerName, address);
SaveCustomer(customer);
}
private Address CreateAddress(string addressString) {
return new Address(addressString);
}
private Customer CreateCustomer(string name, Address address) {
return new Customer(name, address);
}
private void SaveCustomer(Customer customer) {
var repository = new Repository();
repository.Save(customer);
}
}
Command
Query
Command
Query
How to Deal with Side Effects
var stack = new Stack<string>();
stack.Push("value"); // Command
string value = stack.Pop(); // Both query and command
How to Deal with Side Effects
Application
Domain logic Mutating state
Generates artifacts
Uses artifacts to change
the system’s state
How to Deal with Side Effects
Immutable CoreInput Artifacts
Mutable Shell
Exceptions and Readability
public ActionResult CreateEmployee(string name) {
try {
ValidateName(name);
// Rest of the method
return View("Success");
}
catch (ValidationException ex) {
return View("Error", ex.Message);
}
}
private void ValidateName(string name) {
if (string.IsNullOrWhiteSpace(name))
throw new ValidationException("Name cannot be empty");
if (name.Length > 100)
throw new ValidationException("Name is too long");
}
Exceptions and Readability
public Employee CreateEmployee(string name)
{
ValidateName(name);
// Rest of the method
}
Exceptions and Readability
Exceptions for
flow control
Goto
statements=
Exceptions and Readability
Method with
exceptions
Mathematical
function=
Exceptions and Readability
fInput Output
Exceptions
Method
signature
Hidden part
Always prefer return values
over exceptions.
Use Cases for Exceptions
• Exceptions are for exceptional situations
• Exceptions should signalize a bug
• Don’t use exceptions in situations you expect to happen
Use Cases for Exceptions
Validations
Exceptional
situation=
Primitive Obsession
Primitive obsession stands for
using primitive types for
domain modeling.
Drawbacks of Primitive Obsession
public class User
{
public string Email { get; }
public User(string email)
{
Email = email;
}
}
public class User
{
public string Email { get; }
public User(string email)
{
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentException("Email should not be empty");
email = email.Trim();
if (email.Length > 256)
throw new ArgumentException("Email is too long");
if (!email.Contains("@"))
throw new ArgumentException("Email is invalid");
Email = email;
}
}
Drawbacks of Primitive Obsession
Drawbacks of Primitive Obsession
public class Organization
{
public string PrimaryEmail { get; }
public Organization(string primaryEmail)
{
PrimaryEmail = primaryEmail;
}
}
public class Organization
{
public string PrimaryEmail { get; }
public Organization(string primaryEmail)
{
if (string.IsNullOrWhiteSpace(primaryEmail))
throw new ArgumentException("Email should not be empty");
primaryEmail = primaryEmail.Trim();
if (primaryEmail.Length > 256)
throw new ArgumentException("Email is too long");
if (!primaryEmail.Contains("@"))
throw new ArgumentException("Email is invalid");
PrimaryEmail = primaryEmail;
}
}
Drawbacks of Primitive Obsession
Drawbacks of Primitive Obsession
Dishonest signature
public class UserFactory
{
public User CreateUser(string email)
{
return new User(email);
}
}
public int Divide(int x, int y)
{
return x / y;
}
fstring user
Dishonest signature
Drawbacks of Primitive Obsession
Makes code
dishonest
Violates the
DRY principle
Wrap primitive types with
separate classes
Drawbacks of Primitive Obsession
public class UserFactory
{
public User CreateUser(Email email)
{
return new User(email);
}
}
public int Divide(int x, NonZeroInteger y)
{
return x / y;
}
femail user
Honest signature Honest signature
Getting Rid of Primitive Obsession
• Removing duplications
• Method signature honesty
• Stronger type system
The Billion-dollar Mistake
string someString = null;
Customer customer = null;
Employee employee = null;
The Billion-dollar Mistake
“I call it my billion-dollar mistake. It has caused
a billion dollars of pain and damage in the last
forty years.”
Tony Hoare
The Billion-dollar Mistake
public class Organization
{
public Employee GetEmployee(string name)
{
/* ... */
}
}
public class OrganizationRepository
{
public Organization GetById(int id)
{
/* ... */
}
}
The Billion-dollar Mistake
public class MyClassOrNull
{
// either null
public readonly Null Null;
// or actually a MyClass instance
public readonly MyClass MyClass;
}
public class MyClass
{
}
The Billion-dollar Mistake
fInteger MyClass
MyClassOrNull
Dishonest
Mitigating the Billion-dollar Mistake
Maybe<T>
Mitigating the Billion-dollar Mistake
public class OrganizationRepository
{
public Organization GetById(int id)
{
/* ... */
}
}
Maybe<Organization>
Mitigating the Billion-dollar Mistake
public class OrganizationRepository
{
public Maybe<Organization> GetById(int id)
{
/* ... */
}
}
public class Organization
{
public Employee GetEmployee(string name)
{
/* ... */
}
}
Mitigating the Billion-dollar Mistake
public class OrganizationRepository
{
public Maybe<Organization> GetById(int id)
{
/* ... */
}
}
public static int? Divide(int x, int y)
{
if (y == 0)
return null;
return x / y;
}
Honest
Honest
Functional C#
Demo time
Summary
• Functional programming is programming with mathematical functions
• Method signature honesty
• Referential transparency
• Side effects and exceptions make your code dishonest about the
outcome it may produce
• Primitive obsession makes your code dishonest about its input parts
• Nulls make your code dishonest about both its inputs and outputs
• Applying Functional Principles in C# Pluralsight course:
https://app.pluralsight.com/courses/csharp-applying-functional-
principles
THANK YOU
Vladimir Khorikov
@vkhorikov
vkhorikov@eastbanctech.com
202-295-3000
eastbanctech.com

More Related Content

What's hot

Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Basic fundamentals of web application development
Basic fundamentals of web application developmentBasic fundamentals of web application development
Basic fundamentals of web application developmentsofyjohnson18
 
Reactjs workshop
Reactjs workshop Reactjs workshop
Reactjs workshop Ahmed rebai
 
C# quick ref (bruce 2016)
C# quick ref (bruce 2016)C# quick ref (bruce 2016)
C# quick ref (bruce 2016)Bruce Hantover
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptxmaryansagsgao
 
Robot framework Gowthami Goli
Robot framework Gowthami GoliRobot framework Gowthami Goli
Robot framework Gowthami GoliGowthami Buddi
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in JavaTushar B Kute
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 
How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppHow To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppAndolasoft Inc
 
HTML5 Form Validation
HTML5 Form ValidationHTML5 Form Validation
HTML5 Form ValidationIan Oxley
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
React web development
React web developmentReact web development
React web developmentRully Ramanda
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Selenium locators: ID, Name, xpath, CSS Selector advance methods
Selenium locators: ID, Name,  xpath, CSS Selector advance methodsSelenium locators: ID, Name,  xpath, CSS Selector advance methods
Selenium locators: ID, Name, xpath, CSS Selector advance methodsPankaj Dubey
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Javayht4ever
 

What's hot (20)

Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Basic fundamentals of web application development
Basic fundamentals of web application developmentBasic fundamentals of web application development
Basic fundamentals of web application development
 
Reactjs workshop
Reactjs workshop Reactjs workshop
Reactjs workshop
 
C# quick ref (bruce 2016)
C# quick ref (bruce 2016)C# quick ref (bruce 2016)
C# quick ref (bruce 2016)
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptx
 
Robot framework Gowthami Goli
Robot framework Gowthami GoliRobot framework Gowthami Goli
Robot framework Gowthami Goli
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in Java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppHow To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native App
 
HTML5 Form Validation
HTML5 Form ValidationHTML5 Form Validation
HTML5 Form Validation
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
React web development
React web developmentReact web development
React web development
 
Test Complete
Test CompleteTest Complete
Test Complete
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Selenium locators: ID, Name, xpath, CSS Selector advance methods
Selenium locators: ID, Name,  xpath, CSS Selector advance methodsSelenium locators: ID, Name,  xpath, CSS Selector advance methods
Selenium locators: ID, Name, xpath, CSS Selector advance methods
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 

Viewers also liked

Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#Alfonso Garcia-Caro
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented ProgrammingScott Wlaschin
 
Rx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETRx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETJakub Malý
 
A Quick Intro to ReactiveX
A Quick Intro to ReactiveXA Quick Intro to ReactiveX
A Quick Intro to ReactiveXTroy Miles
 
Configuring SSL on NGNINX and less tricky servers
Configuring SSL on NGNINX and less tricky serversConfiguring SSL on NGNINX and less tricky servers
Configuring SSL on NGNINX and less tricky serversAxilis
 
NuGet Must Haves for LINQ
NuGet Must Haves for LINQNuGet Must Haves for LINQ
NuGet Must Haves for LINQAxilis
 
Functional programming in C#
Functional programming in C#Functional programming in C#
Functional programming in C#Thomas Jaskula
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
C# features through examples
C# features through examplesC# features through examples
C# features through examplesZayen Chagra
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegantalenttransform
 
1.7 functional programming
1.7 functional programming1.7 functional programming
1.7 functional programmingfuturespective
 
The essence of Reactive Programming
The essence of Reactive ProgrammingThe essence of Reactive Programming
The essence of Reactive ProgrammingEddy Bertoluzzo
 
C# 6.0 - DotNetNotts
C# 6.0 - DotNetNottsC# 6.0 - DotNetNotts
C# 6.0 - DotNetNottscitizenmatt
 
Elm & Elixir: Functional Programming and Web
Elm & Elixir: Functional Programming and WebElm & Elixir: Functional Programming and Web
Elm & Elixir: Functional Programming and WebPublitory
 
Designing with Capabilities
Designing with CapabilitiesDesigning with Capabilities
Designing with CapabilitiesScott Wlaschin
 
Real-World Functional Programming @ Incubaid
Real-World Functional Programming @ IncubaidReal-World Functional Programming @ Incubaid
Real-World Functional Programming @ IncubaidNicolas Trangez
 

Viewers also liked (20)

Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#
 
The taste of F#
The taste of F#The taste of F#
The taste of F#
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Rx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETRx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NET
 
A Quick Intro to ReactiveX
A Quick Intro to ReactiveXA Quick Intro to ReactiveX
A Quick Intro to ReactiveX
 
New features in C# 6
New features in C# 6New features in C# 6
New features in C# 6
 
Configuring SSL on NGNINX and less tricky servers
Configuring SSL on NGNINX and less tricky serversConfiguring SSL on NGNINX and less tricky servers
Configuring SSL on NGNINX and less tricky servers
 
NuGet Must Haves for LINQ
NuGet Must Haves for LINQNuGet Must Haves for LINQ
NuGet Must Haves for LINQ
 
Functional programming in C#
Functional programming in C#Functional programming in C#
Functional programming in C#
 
Dynamic C#
Dynamic C# Dynamic C#
Dynamic C#
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
C# features through examples
C# features through examplesC# features through examples
C# features through examples
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
1.7 functional programming
1.7 functional programming1.7 functional programming
1.7 functional programming
 
The essence of Reactive Programming
The essence of Reactive ProgrammingThe essence of Reactive Programming
The essence of Reactive Programming
 
Frp
FrpFrp
Frp
 
C# 6.0 - DotNetNotts
C# 6.0 - DotNetNottsC# 6.0 - DotNetNotts
C# 6.0 - DotNetNotts
 
Elm & Elixir: Functional Programming and Web
Elm & Elixir: Functional Programming and WebElm & Elixir: Functional Programming and Web
Elm & Elixir: Functional Programming and Web
 
Designing with Capabilities
Designing with CapabilitiesDesigning with Capabilities
Designing with Capabilities
 
Real-World Functional Programming @ Incubaid
Real-World Functional Programming @ IncubaidReal-World Functional Programming @ Incubaid
Real-World Functional Programming @ Incubaid
 

Similar to Functional Programming with C#

Computer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxComputer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxJohnRehldeGracia
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.pptpsundarau
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programmingDavid Giard
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScriptAleš Najmann
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 

Similar to Functional Programming with C# (20)

Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Computer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxComputer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptx
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.ppt
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
Clean code
Clean codeClean code
Clean code
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Java 2
Java   2Java   2
Java 2
 

More from EastBanc Tachnologies

Unpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesUnpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesEastBanc Tachnologies
 
Azure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectAzure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectEastBanc Tachnologies
 
Getting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesGetting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesEastBanc Tachnologies
 
Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0EastBanc Tachnologies
 
Highlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceHighlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceEastBanc Tachnologies
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 
Async Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsAsync Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsEastBanc Tachnologies
 
EastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Tachnologies
 
EastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Tachnologies
 
EastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Tachnologies
 
EastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Tachnologies
 
Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#EastBanc Tachnologies
 

More from EastBanc Tachnologies (14)

Unpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesUnpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc Technologies
 
Azure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectAzure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your project
 
Getting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesGetting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics services
 
DevOps with Kubernetes
DevOps with KubernetesDevOps with Kubernetes
DevOps with Kubernetes
 
Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0
 
Highlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceHighlights from MS build\\2016 Conference
Highlights from MS build\\2016 Conference
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Estimating for Fixed Price Projects
Estimating for Fixed Price ProjectsEstimating for Fixed Price Projects
Estimating for Fixed Price Projects
 
Async Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsAsync Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and Pitfalls
 
EastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and Innovation
 
EastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint Portfolio
 
EastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI Portfolio
 
EastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS Portfolio
 
Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%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 tembisamasabamasaba
 
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...Shane Coughlan
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%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 midrandmasabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
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?WSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%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 tembisamasabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park 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 2024VictoriaMetrics
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
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-learnAmarnathKambale
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 

Recently uploaded (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%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
 
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...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%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
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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?
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%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
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
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
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
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
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 

Functional Programming with C#

  • 2. What is Functional Programming? • Side-effect free programming? • Higher order functions? • Use of a functional language like F# / Haskell / Scala?
  • 3. Functional programming is programming with mathematical functions.
  • 5. What is Functional Programming? Mathematical function Class method=
  • 6. What is Functional Programming? f Referential transparency: same input – same result Information about possible inputs and outcomes
  • 7. What is Functional Programming? public double Calculate(double x, double y) { return x * x + y * y; } public long TicksElapsedFrom(int year) { DateTime now = DateTime.Now; DateTime then = new DateTime(year, 1, 1); return (now - then).Ticks; } Same input – same result Result is always different
  • 8. What is Functional Programming? public static int Divide(int x, int y) { return x / y; } f Integer Integer Integer 1 0 ? DivideByZeroException
  • 9. Method Signature Honesty Method signature All possible inputs All possible outcomes
  • 10. Method Signature Honesty Honest signatureDishonest signature public static int Divide(int x, int y) { return x / y; } public static int Divide(int x, NonZeroInteger y) { return x / y.Value; } public static int? Divide(int x, int y) { if (y == 0) return null; return x / y; }
  • 11. Mathematical Function • Honest • Has precisely defined input and output • Referentially transparent • Doesn’t affect or refer to the global state
  • 12. Why Functional Programming? Composable Easy to reason about Easier to unit test Reducing complexity
  • 13. Immutability • Immutability • Inability to change data • State • Data that changes over time • Side effect • A change that is made to some state
  • 17. Why Does Immutability Matter? • Increased readability • A single place for validating invariants • Automatic thread safety
  • 18. How to Deal with Side Effects Command–query separation principle Command Query Produces side effects Side-effect free Returns void Returns non-void
  • 19. How to Deal with Side Effects public class CustomerService { public void Process(string customerName, string addressString) { Address address = CreateAddress(addressString); Customer customer = CreateCustomer(customerName, address); SaveCustomer(customer); } private Address CreateAddress(string addressString) { return new Address(addressString); } private Customer CreateCustomer(string name, Address address) { return new Customer(name, address); } private void SaveCustomer(Customer customer) { var repository = new Repository(); repository.Save(customer); } } Command Query Command Query
  • 20. How to Deal with Side Effects var stack = new Stack<string>(); stack.Push("value"); // Command string value = stack.Pop(); // Both query and command
  • 21. How to Deal with Side Effects Application Domain logic Mutating state Generates artifacts Uses artifacts to change the system’s state
  • 22. How to Deal with Side Effects Immutable CoreInput Artifacts Mutable Shell
  • 23. Exceptions and Readability public ActionResult CreateEmployee(string name) { try { ValidateName(name); // Rest of the method return View("Success"); } catch (ValidationException ex) { return View("Error", ex.Message); } } private void ValidateName(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ValidationException("Name cannot be empty"); if (name.Length > 100) throw new ValidationException("Name is too long"); }
  • 24. Exceptions and Readability public Employee CreateEmployee(string name) { ValidateName(name); // Rest of the method }
  • 25. Exceptions and Readability Exceptions for flow control Goto statements=
  • 26. Exceptions and Readability Method with exceptions Mathematical function=
  • 27. Exceptions and Readability fInput Output Exceptions Method signature Hidden part
  • 28. Always prefer return values over exceptions.
  • 29. Use Cases for Exceptions • Exceptions are for exceptional situations • Exceptions should signalize a bug • Don’t use exceptions in situations you expect to happen
  • 30. Use Cases for Exceptions Validations Exceptional situation=
  • 31. Primitive Obsession Primitive obsession stands for using primitive types for domain modeling.
  • 32. Drawbacks of Primitive Obsession public class User { public string Email { get; } public User(string email) { Email = email; } }
  • 33. public class User { public string Email { get; } public User(string email) { if (string.IsNullOrWhiteSpace(email)) throw new ArgumentException("Email should not be empty"); email = email.Trim(); if (email.Length > 256) throw new ArgumentException("Email is too long"); if (!email.Contains("@")) throw new ArgumentException("Email is invalid"); Email = email; } } Drawbacks of Primitive Obsession
  • 34. Drawbacks of Primitive Obsession public class Organization { public string PrimaryEmail { get; } public Organization(string primaryEmail) { PrimaryEmail = primaryEmail; } }
  • 35. public class Organization { public string PrimaryEmail { get; } public Organization(string primaryEmail) { if (string.IsNullOrWhiteSpace(primaryEmail)) throw new ArgumentException("Email should not be empty"); primaryEmail = primaryEmail.Trim(); if (primaryEmail.Length > 256) throw new ArgumentException("Email is too long"); if (!primaryEmail.Contains("@")) throw new ArgumentException("Email is invalid"); PrimaryEmail = primaryEmail; } } Drawbacks of Primitive Obsession
  • 36. Drawbacks of Primitive Obsession Dishonest signature public class UserFactory { public User CreateUser(string email) { return new User(email); } } public int Divide(int x, int y) { return x / y; } fstring user Dishonest signature
  • 37. Drawbacks of Primitive Obsession Makes code dishonest Violates the DRY principle
  • 38. Wrap primitive types with separate classes
  • 39. Drawbacks of Primitive Obsession public class UserFactory { public User CreateUser(Email email) { return new User(email); } } public int Divide(int x, NonZeroInteger y) { return x / y; } femail user Honest signature Honest signature
  • 40. Getting Rid of Primitive Obsession • Removing duplications • Method signature honesty • Stronger type system
  • 41. The Billion-dollar Mistake string someString = null; Customer customer = null; Employee employee = null;
  • 42. The Billion-dollar Mistake “I call it my billion-dollar mistake. It has caused a billion dollars of pain and damage in the last forty years.” Tony Hoare
  • 43. The Billion-dollar Mistake public class Organization { public Employee GetEmployee(string name) { /* ... */ } } public class OrganizationRepository { public Organization GetById(int id) { /* ... */ } }
  • 44. The Billion-dollar Mistake public class MyClassOrNull { // either null public readonly Null Null; // or actually a MyClass instance public readonly MyClass MyClass; } public class MyClass { }
  • 45. The Billion-dollar Mistake fInteger MyClass MyClassOrNull Dishonest
  • 46. Mitigating the Billion-dollar Mistake Maybe<T>
  • 47. Mitigating the Billion-dollar Mistake public class OrganizationRepository { public Organization GetById(int id) { /* ... */ } } Maybe<Organization>
  • 48. Mitigating the Billion-dollar Mistake public class OrganizationRepository { public Maybe<Organization> GetById(int id) { /* ... */ } } public class Organization { public Employee GetEmployee(string name) { /* ... */ } }
  • 49. Mitigating the Billion-dollar Mistake public class OrganizationRepository { public Maybe<Organization> GetById(int id) { /* ... */ } } public static int? Divide(int x, int y) { if (y == 0) return null; return x / y; } Honest Honest
  • 51. Summary • Functional programming is programming with mathematical functions • Method signature honesty • Referential transparency • Side effects and exceptions make your code dishonest about the outcome it may produce • Primitive obsession makes your code dishonest about its input parts • Nulls make your code dishonest about both its inputs and outputs • Applying Functional Principles in C# Pluralsight course: https://app.pluralsight.com/courses/csharp-applying-functional- principles

Editor's Notes

  1. Composable: can be treated in isolation Easier to reason about, no need to fall down to implementation details Easier to unit test, just provide input and verify output, no mocks Reducing complexity: fewer bugs, better maintainability The principles – referential transparency and method signature honesty - look quite simple, but if applied in practice, have interesting consequences. Let’s see what those consequences are.
  2. When we talked about the concept of method signature honesty in the previous module, we discussed that whenever you define a method, you should try to put into its signature the information about all its possible outcomes. By defining a method with a side-effect, we loose this information. The signature of such a method no longer tells us what the actual result of the operation is. Hinders our ability to reason about the code.
  3. So, how to fix that? Lift all possible outcomes to a signature level.
  4. - Immutability does exactly this: it forces you to be honest about what the method does.
  5. Cannot avoid dealing with side effects
  6. Make shell as dumb as possible