SlideShare a Scribd company logo
Mixing functional and object oriented approaches to programming in C# Mark Needham
A bit of context
ThoughtWorks delivery projects
Web applications with somewhat complicated domains
5-15 developers on a team
Projects running for 6-12 months
All this means that we want to write code which is…
Easy to understand
Easy to change
Which leads us to what this talk is all about…
Organisation of code ‘ The Lush Landscape of Languages’ - The ThoughtWorks Anthology Rebecca Parsons
How might functional programming help us with that?
First class functions
“ A programming language is said to support first class functions  if functions can be created during the execution of a program, stored in data structures, passed as arguments to other functions, and returned as the values of other functions” Wikipedia
Immutability
Lazy evaluation
Recursion
Pattern matching
This is all very cool but…
Object Oriented design still has its place
Encapsulation
Abstraction
So how do these two paradigms work together?
Programming in the small/medium/large http://weblogs.asp.net/podwysocki/archive/2009/12/14/going-hybrid-implementing-a-shopping-cart-in-f.aspx
In the large…  “a high level that affects as well as crosscuts multiple classes and functions”
In the medium…  “a single API or group of related APIs in such things as classes, interfaces, modules”
In the small…  “individual function/method bodies”
Large Medium Small
Large Medium Small
LINQ
a.k.a. Functional collection parameters http://billsix.blogspot.com/2008/03/functional-collection-patterns-in-ruby.html
“powerful abstractions over collections”
“ the use of high-order functions is  extremely useful for separating the collection's concerns from the user of the collection”
for loop becomes less useful
Don’t just use ForEach!
Code becomes more declarative
Declarative? “a statement specifies some aspect of the desired answer with no notion of how that answer is to be determined” ‘ The Lush Landscape of Languages’ - The ThoughtWorks Anthology Rebecca Parsons
Requires a mental shift from imperative thinking
Transformational mindset Patrick Logan in the comments section http://www.markhneedham.com/blog/2010/01/20/functional-collectional-parameters-some-thoughts/
Current Input ??? ??? ??? Desired Output
Going from one collection to another
var  words =  new  List<string>  { “hello”, “world” }; var  upperCaseWords =  new  List<string>(); foreach  (var word  in  words) { upperCaseWords.Add(word.ToUpper()); }
a.k.a. map
“ hello”, “world” ???? “HELLO”, “WORLD”
“hello”, “world” Select “HELLO”, “WORLD”
var  words =  new  List<string>  { “hello”, “world” }; var  upperCaseWords =  words.Select(w => w.ToUpper());
Remove values we don’t want
var  words =  new  List<string>   {“hello”, “world”}; var  wordsWithH =  new  List<string>(); foreach  (var word  in  words) { if(word.Contains(“h”) wordsWithH.Add(word); }
a.k.a. filter
“ hello”, “world” ???? “hello”
“ hello”, “world” Where “hello”
var  words =  new  List<string>   {“hello”, “world”} ; var  wordsWithH =  words.Where(w => w.Contains(“h”));
Summing some values
var  values =  new  List<int> { 1,2,3 }; var  total =  0; foreach  (var value  in  values) { total += value; }
a.k.a. reduce
1, 2, 3 ??? 6
1, 2, 3 Sum 6
var  values =  new  List<int> { 1,2,3 }; var  total = val ues.Sum(v => v);
Some examples from projects
Getting the first value that matches a criteria
Foo(“mark”, true), Foo(“dave”, false), Foo(“mike”, true) ???? Foo(“mark”, true)
Foo(“mark”, true), Foo(“dave”, false), Foo(“mike”, true) Where Foo(“mark”, true), Foo(“mike”, true) ??? Foo(“mark”, true)
Foo(“mark”, true), Foo(“dave”, false), Foo(“mike”, true) Where Foo(“mark”, true), Foo(“mike”, true) First Foo(“mark”, true)
var  foos =  new  List<Foo>  {   new Foo(“mark”, true),    new Foo(“dave”, false),   new Foo(“mike”, true)  }; var  firstSpecialFoo =  foos.   Where(f => f.HasSpecialFlag()).   First());
var  foos =  new  List<Foo>  {   new Foo(“mark”, true),    new Foo(“dave”, false),   new Foo(“mike”, true)  }; var  firstSpecialFoo =  foos.First(f => f.HasSpecialFlag());
Removing some columns from a dataset
a,b,c,d,e,f ????   “a,d,e,f”
a,b,c,d,e,f Where IEnumerable of a, d, e, f ???   “a,d,e,f”
a,b,c,d,e,f Where IEnumerable of a, d, e, f ??? String.Join  on [a, d, e, f] “a,d,e,f”
a,b,c,d,e,f Where IEnumerable of a, d, e, f ToArray() String.Join  on [a, d, e, f]  “a,d,e,f”
var  aRow =  “a, b, c, d, e, f”; var  newRow =  String.Join(“,”,   aRow   .Split(‘,’)   .Where((_, idx) => !(idx == 1 || idx == 2))   .ToArray());
var  aRow =  “a, b, c, d, e, f”; var  rowWithColumnsRemoved =  aRow   .Split(‘,’)   .Where((_, idx) => !(idx == 1 || idx == 2))   .ToArray());  var  newRow = String.Join(“,”, rowWithColumnsRemoved);
Checking if any parameters are null
public class  SomeObject {   public  SomeObject(string p1, string p2,    string p3)   {   if  (p1 ==  null )    throw new Exception(...);   if  (p2 ==  null )    throw new Exception(...);   if  (p3 ==  null )    throw new Exception(...);   // rest of constructor logic   } }
public class  SomeObject {   public  SomeObject(string p1, string p2,    string p3)   {   var  params = new List<string> {p1, p2, p3};   if  (params.Any(p => p == null)    throw new Exception(...);    // rest of constructor logic   } }
Some lessons from the wild
Dealing with the null collection
public   int  SumNumbers(List< int > list) { if(list ==  null ) return 0; return list.Sum(v => v); }
public  IEnumerable<T> EmptyIfNull( this  IEnumerable<T> collection) { if(collection ==  null ) return  new  List<T>(); return collection; } Chris Ammerman in the comments section http://www.markhneedham.com/blog/2009/06/16/functional-collection-parameters-handling-the-null-collection/
public   int  SumNumbers(List< int > list) { return list. EmptyIfNull(). Sum(v => v); }
LINQ and the forgotten abstraction
Avoid passing lists around
public class  Quote { public  List<Coverage> Coverages  {  get; set;  } }
Later on in the view…
<% var coverages = Model.Quote.Coverages; %> <% if(coverages.Where( c => c.Name == “coverageType1”) %> ... <% if(coverages.Where( c => c.Name == “coverageType2”) %> ... <% if(coverages.Where( c => c.Name == “coverageType3”) %>
Objects as the mechanism for encapsulation
public class  Coverages { private   readonly  List<Coverage> coverages; public  Coverages(List<Coverage> coverages) { this.coverages = new List<Coverage>(coverages); } public  Coverage CoverageType1 {   get    {    return  coverages.Where( c => c.Name == “coverageType1”;    } } }
LINQ is duplication too!
public class  Coverages { public  Coverage CoverageType1 {   get    {    return  coverages.Where( c => c.Name == “coverageType1”;    } } public  Coverage CoverageType2 {   get    {    return  coverages.Where( c => c.Name == “coverageType2”;    } } }
public class  Coverages { public  Coverage CoverageType1 { get {  return     CoverageByName(“coverageType1”); } } public  Coverage CoverageType2 { get {  return     CoverageByName(“coverageType2”); } } public  Coverage CoverageBy(string name) { return  coverages.Where(c => c.Name == name); } }
Don’t forget “extract method”
var  someFoos =  new  List<Foo>() // put some foos in the list someFoos.Select(f =>  new  NewFoo    { Property1 = f.Property1 ...   });
var  someFoos =  new  List<Foo>() // put some foos in the list someFoos.Select(f => CreateNewFooFrom(f));
Naming lambda variables
Putting functions in maps
public void  SomeMethodParsing( string  input) { if  (input == “input1”)  { someMethod(input); } else if  (input == “input2”) { someOtherMethod(input); } // and so on }
Dictionary< string , Action< string >> inputs =    new Dictionary< string , Action< string >>    { { “input1” , someMethod },    { “input2” , someOtherMethod } }; public void  SomeMethodParsing( string  input) { var  method = inputs[input]; method(input); }
Large Medium Small
Using functions to simplify some GOF patterns
Action
Func
public class  SomeObject { private readonly IStrategy strategy; public Foo(IStrategy strategy) { this.strategy = strategy; } public void DoSomething(string value) { strategy.DoSomething(value); } }
public class  Strategy : IStrategy { public void DoSomething(string value) { // do something with string } }
public class  SomeObject { private readonly Action<string> strategy; public Foo(Action<string> strategy) { this. strategy = strategy; } public void DoSomething(string value) {   strategy(value); } }
Need to ensure we don’t lose readability/understandability
The hole in the middle pattern Brian Hurt http://enfranchisedmind.com/blog/posts/the-hole-in-the-middle-pattern/
Common beginning and end. Only the middle differs
public class  ServiceCache<Service> { protected  Res FromCacheOrService <Req, Res>(Func<Res> serviceCall, Req request) { var cachedRes = cache.RetrieveIfExists( typeof(Service), typeof(Res), request);   if(cachedRes == null)   { cachedRes = serviceCall(); cache.Add(typeof(Service), request, cachedRes);   } return (Res) cachedRes; } }
public class  CachedService : ServiceCache<IService> { public  MyResult GetMyResult(MyRequest request) { return FromCacheOrService( () => service.GetMyResult(request), request); } }
Other ideas I’m intrigued about
The option type
The nested closure
File.open(“someFile.txt”, ‘w’)  do  |out| out  <<  “add something to file” end
public class MyFile  {   public static void Open(string filePath,  Action<StreamWriter> block)   {   using(var writer = new StreamWriter())    {   block(writer );   }   } }
MyFile.Open(“c:\\mark.txt”, f =>  f.WriteLine(“some random text”));
Writing extension methods to create functional abstractions
Learning more
 
3 things to take away
The transformational mindset
Objects are still the mechanism for encapsulation
Simplify GOF design patterns by using functions
Thanks to… Dave Cameron (not that one!) who I worked with on the structure and general content of the talk. Mike Wagg, Brian Blignaut, Chris Owen for reviewing the talk and giving their input.
Questions? Mark Needham http://www.markhneedham.com/blog/ [email_address] Twitter: markhneedham

More Related Content

What's hot (20)

PPTX
Clean code
Henrique Smoco
 
PPTX
clean code book summary - uncle bob - English version
saber tabatabaee
 
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
PDF
Logic programming a ruby perspective
Norman Richards
 
PPTX
Clean code
ifnu bima
 
PPTX
Linq Sanjay Vyas
rsnarayanan
 
PDF
Java script introducation & basics
H K
 
PDF
Functional programming in java
John Ferguson Smart Limited
 
PDF
Declare Your Language: Transformation by Strategic Term Rewriting
Eelco Visser
 
PPT
Functional Programming In Java
Andrei Solntsev
 
PDF
Declare Your Language: Name Resolution
Eelco Visser
 
PPTX
Javascript basics
Solv AS
 
PPT
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
PPTX
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
PDF
Java Generics - by Example
Ganesh Samarthyam
 
PPTX
Clean Code: Chapter 3 Function
Kent Huang
 
PDF
The Ring programming language version 1.7 book - Part 35 of 196
Mahmoud Samir Fayed
 
PPTX
Kpi driven-java-development-fn conf
Anirban Bhattacharjee
 
PPTX
Clean Code Development
Peter Gfader
 
PPT
Javascript built in String Functions
Avanitrambadiya
 
Clean code
Henrique Smoco
 
clean code book summary - uncle bob - English version
saber tabatabaee
 
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
Logic programming a ruby perspective
Norman Richards
 
Clean code
ifnu bima
 
Linq Sanjay Vyas
rsnarayanan
 
Java script introducation & basics
H K
 
Functional programming in java
John Ferguson Smart Limited
 
Declare Your Language: Transformation by Strategic Term Rewriting
Eelco Visser
 
Functional Programming In Java
Andrei Solntsev
 
Declare Your Language: Name Resolution
Eelco Visser
 
Javascript basics
Solv AS
 
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Java Generics - by Example
Ganesh Samarthyam
 
Clean Code: Chapter 3 Function
Kent Huang
 
The Ring programming language version 1.7 book - Part 35 of 196
Mahmoud Samir Fayed
 
Kpi driven-java-development-fn conf
Anirban Bhattacharjee
 
Clean Code Development
Peter Gfader
 
Javascript built in String Functions
Avanitrambadiya
 

Similar to Mixing functional and object oriented approaches to programming in C# (20)

PPSX
What's New In C# 7
Paulo Morgado
 
ODP
Ast transformations
HamletDRC
 
PPT
JBUG 11 - Scala For Java Programmers
Tikal Knowledge
 
ODP
Scala introduction
Alf Kristian Støyle
 
PDF
Java 8 Workshop
Mario Fusco
 
PDF
Java Class Design
Ganesh Samarthyam
 
PPT
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
PDF
Functional Programming You Already Know
Kevlin Henney
 
PPSX
Tuga IT 2017 - What's new in C# 7
Paulo Morgado
 
PDF
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
James Titcumb
 
PPTX
Groovy
Zen Urban
 
PPTX
Java gets a closure
Tomasz Kowalczewski
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
ODP
Scala 2 + 2 > 4
Emil Vladev
 
PPTX
Clean Code
Nascenia IT
 
PDF
FP in Java - Project Lambda and beyond
Mario Fusco
 
PPT
TechTalk - Dotnet
heinrich.wendel
 
PDF
Introduction to Scalding and Monoids
Hugo Gävert
 
PDF
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Codemotion
 
PDF
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
James Titcumb
 
What's New In C# 7
Paulo Morgado
 
Ast transformations
HamletDRC
 
JBUG 11 - Scala For Java Programmers
Tikal Knowledge
 
Scala introduction
Alf Kristian Støyle
 
Java 8 Workshop
Mario Fusco
 
Java Class Design
Ganesh Samarthyam
 
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
Functional Programming You Already Know
Kevlin Henney
 
Tuga IT 2017 - What's new in C# 7
Paulo Morgado
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
James Titcumb
 
Groovy
Zen Urban
 
Java gets a closure
Tomasz Kowalczewski
 
TypeScript Introduction
Dmitry Sheiko
 
Scala 2 + 2 > 4
Emil Vladev
 
Clean Code
Nascenia IT
 
FP in Java - Project Lambda and beyond
Mario Fusco
 
TechTalk - Dotnet
heinrich.wendel
 
Introduction to Scalding and Monoids
Hugo Gävert
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Codemotion
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
James Titcumb
 
Ad

More from Mark Needham (14)

PDF
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Mark Needham
 
PDF
This week in Neo4j - 3rd February 2018
Mark Needham
 
PDF
Building a recommendation engine with python and neo4j
Mark Needham
 
PDF
Graph Connect: Tuning Cypher
Mark Needham
 
PDF
Graph Connect: Importing data quickly and easily
Mark Needham
 
PDF
Graph Connect Europe: From Zero To Import
Mark Needham
 
PDF
Optimizing cypher queries in neo4j
Mark Needham
 
PPTX
Football graph - Neo4j and the Premier League
Mark Needham
 
PDF
The Football Graph - Neo4j and the Premier League
Mark Needham
 
PPTX
Scala: An experience report
Mark Needham
 
PPTX
Visualisations
Mark Needham
 
PPTX
Mixing functional programming approaches in an object oriented language
Mark Needham
 
PPT
Mixing functional and object oriented approaches to programming in C#
Mark Needham
 
PDF
F#: What I've learnt so far
Mark Needham
 
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Mark Needham
 
This week in Neo4j - 3rd February 2018
Mark Needham
 
Building a recommendation engine with python and neo4j
Mark Needham
 
Graph Connect: Tuning Cypher
Mark Needham
 
Graph Connect: Importing data quickly and easily
Mark Needham
 
Graph Connect Europe: From Zero To Import
Mark Needham
 
Optimizing cypher queries in neo4j
Mark Needham
 
Football graph - Neo4j and the Premier League
Mark Needham
 
The Football Graph - Neo4j and the Premier League
Mark Needham
 
Scala: An experience report
Mark Needham
 
Visualisations
Mark Needham
 
Mixing functional programming approaches in an object oriented language
Mark Needham
 
Mixing functional and object oriented approaches to programming in C#
Mark Needham
 
F#: What I've learnt so far
Mark Needham
 
Ad

Recently uploaded (20)

PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 

Mixing functional and object oriented approaches to programming in C#

Editor's Notes

  • #2: So this talk is titled ^ and it will be a summary of some of the ways we’ve made use of the functional style programming constructs introduced in C#3.0 on several projects I’ve worked on over the last year and a half.