際際滷

際際滷Share a Scribd company logo
Micropatterns
Learning to reach for the right tool
Hi! Im Cameron
(@cameronp)
Micropatterns
Micropatterns
Micropatterns
Micropatterns
Micropatterns
Time for a 壊岳看姻霞
October, 2014
Micropatterns
BASIC C
Pascal
C++
PythonJava
Ruby
C#
Micropatterns
But it didnt work this
time
Time passes
Micropatterns
Micropatterns
Micropatterns
Exercises
 https://projecteuler.net/
 http://adventofcode.com/
 http://exercism.io/
Many Small Projects > One Big Project
And this time it stuck
I was suddenly faster and more
comfortable in Elixir than in any
language I know
What happened?
OTP?
Nope
M庄界姻看沿温岳岳艶姻稼壊
Micropatterns
Micropatterns
def categories(num)
categories = []
while categories.length < num do
category = fetch('commerce.department')
categories << category unless categories.
include?(category)
end
categories
end
Ruby example
Mutation vs Transformation
Mutation vs Transformation
Micropattern #1: Pipelines
Real World Example
318,Bulah,Dicki,282,37234
306,Dante,Ankunding,285,23140
317,Monserrat,Mraz,286,35000
303,Cesar,Mann,284,54647
312,Arjun,Zulauf,286,37397
297,Ariel,Wisoky,284,31875
309,Herminia,Heaney,285,50981
310,Terrence,Macejkovic,285,38499
287,Abbigail,Miller,282,23391
282,Lavon,Kshlerin,281,46101
290,Joelle,Abbott,282,35470
. . .
defmodule Phb.Employee do
defstruct [ id: 0,
first_name: "",
last_name: "" ,
salary: 0,
manager: nil
]
end
def load(filename  @default_file) do
filename
|> read
|> parse
|> validate
end
def read(file) do
file
|> File.read!
|> String.split("n", trim: true)
|> Enum.map(&String.split(&1, ","))
end
Enum.map(&String.split(&1, ","))
Micropattern #2: Strategy
through higher order functions
Enum.map(&String.split(&1, ","))
Enum.map takes a 1-arity
function
But String.spit/2 is 2-
arity
What to do?
iex(2)> &String.split(&1, ",")
iex(2)> &String.split(&1, ",")
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(2)> &String.split(&1, ",")
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(3)> splitByCommas = &String.split(&1, ",")
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(2)> &String.split(&1, ",")
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(3)> splitByCommas = &String.split(&1, ",")
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(4)> splitByCommas.("1,2,3")
["1", "2", "3"]
def read(file) do
file
|> File.read!
|> String.split("n", trim: true)
|> Enum.map(&String.split(&1, ","))
end
iex(7)> Phb.Employee.Loader.load
[["318", "Bulah", "Dicki", "282", "37234"],
["306", "Dante", "Ankunding", "285", "23140"],
["317", "Monserrat", "Mraz", "286", "35000"],
["303", "Cesar", "Mann", "284", "54647"],
["312", "Arjun", "Zulauf", "286", "37397"],
def load(filename  @default_file) do
filename
|> read
|> parse
|> validate
end
def load(filename  @default_file) do
filename
|> read
|> parse
|> validate
end
Micropattern #3: Handling the
Happy Case with pattern matching
def parse_record([id_s, fname, lname, mgr_s, salary_s]),
do:
def parse_record([id_s, fname, lname, mgr_s, salary_s]),
do:
%Phb.Employee{
id: to_int(id_s),
first_name: fname,
last_name: lname,
manager: to_int(mgr_s),
salary: to_int(salary_s)
}
What if there arent five
elements in the list?
Well itll crash
Well itll crash
(And maybe thats ok)
def load(filename  @default_file) do
filename
|> read
|> parse
|> validate
end
How can validation be thought
of in terms of transformation?
defmodule Phb.Employee do
defstruct [ id: 0,
first_name: "",
last_name: "" ,
salary: 0,
manager: nil ]
end
defmodule Phb.Employee do
defstruct [ id: 0,
first_name: "",
last_name: "" ,
salary: 0,
manager: nil,
errors: []]
end
def valid?(%Employee{errors[]}), do: true
def valid?(%Employee{}), do: false
def add_error(%Employee{} = e, error), do:
%Employee{e | errors: [error | e.errors]}
Ok, so were ready to
perform validations
But Im not going to..
Because theres too many
micropatterns for one talk!
The #1 thing people report
as difficult:
Recursion.
Recursion.
def categories(num)
categories = []
while categories.length < num do
category = fetch('commerce.department')
categories << category unless categories.
include?(category)
end
categories
end
Ruby example
def fetch_category, do: :rand.uniform(100)
def fetch_category, do: :rand.uniform(100)
def categories(n), do: categories(n, [])
Recursion rule #1: Think about
the termination case first
def categories(n), do: categories(n, [])
def categories(0, result), do: result
def categories(n), do: categories(n, [])
def categories(0, result), do: result
def categories(n, result) do
new = fetch_category
case (new in result) do
true -> categories(n, result)
false -> categories(n - 1, [new | result])
end
end
Lets step back for a
moment
Why are we doing this?
Two reasons
#1: You will become more
comfortable writing Elixir
#2: In Elixir, Micropatterns and
Patterns are the same thing
Micropatterns
In OOP, you have objects in the
large, and methods in the small
In FP, we have functions in the
large, and functions in the small
Example: The way we added
errors to an employee struct
Example: The way we added
errors to an employee struct
def add_error(%Employee{} = e, error), do:
%Employee{e | errors: [error | e.errors]}
def add_error(%Employee{} = e, error), do:
%Employee{e | errors: [error | e.errors]}
This is exactly how plugs
work in Phoenix
So if you get comfortable
with these small patterns
 youll find the big architectural
patterns easy to understand
Micropatterns
Ok. Lets try something
harder
318,Bulah,Dicki,282,37234
306,Dante,Ankunding,285,23140
317,Monserrat,Mraz,286,35000
303,Cesar,Mann,284,54647
312,Arjun,Zulauf,286,37397
297,Ariel,Wisoky,284,31875
309,Herminia,Heaney,285,50981
310,Terrence,Macejkovic,285,38499
287,Abbigail,Miller,282,23391
282,Lavon,Kshlerin,281,46101
290,Joelle,Abbott,282,35470
. . .
%Employee{manager: nil,
reports: []}
%Employee{
reports:[]}
%Employee{
reports:[]}
%Employee{
reports:[]}
%Employee{
reports:[]}
%Employee{
reports:[]}
%Employee{
reports:[]}
%Employee{
reports:[]
Where to begin?
%Employee{manager: nil,
reports: []}
def add_report(org, new_employee)
def add_report(org, new_employee)
Takes the top of an organization, and a
new employee
def add_report(org, new_employee)
Takes the top of an organization, and a
new employee
and returns either the org with the
employee added or the org
unchanged
alias Phb.Employee, as: E
def add_report(nil, %E{manager: nil} = report),
do: report
alias Phb.Employee, as: E
def add_report(nil, %E{manager: nil} = report),
do: report
def add_report(nil, _not_a_boss), do: nil
alias Phb.Employee, as: E
def add_report(nil, %E{manager: nil} = report),
do: report
def add_report(nil, _not_a_boss), do: nil
def add_report(%E{id: m_id} = m, %E{manager:
m_id} = r) do
%E{m | reports: [r | m.reports]}
end
alias Phb.Employee, as: E
def add_report(nil, %E{manager: nil} = report),
do: report
def add_report(nil, _not_a_boss), do: nil
def add_report(%E{id: m_id} = m, %E{manager:
m_id} = r) do
%E{m | reports: [r | m.reports]}
end
def add_report(m, r) do
new_reports =
m.reports
|> Enum.map(fn rep -> add_report(rep, r) end)
%E{m | reports: new_reports}
end
def add_report(m, r) do
new_reports =
m.reports
|> Enum.map(fn rep -> add_report(rep, r) end)
%E{m | reports: new_reports}
end
def add_all_reports(reports, org)
def add_all_reports([], org), do: org
def add_all_reports([], org), do: org
def add_all_reports([rep | rest], org) do
def add_all_reports([], org), do: org
def add_all_reports([rep | rest], org) do
case add_report(org, rep) do
def add_all_reports([], org), do: org
def add_all_reports([rep | rest], org) do
case add_report(org, rep) do
^org ->
def add_all_reports([], org), do: org
def add_all_reports([rep | rest], org) do
case add_report(org, rep) do
^org -> add_all_reports(rest ++ [rep], org)
def add_all_reports([], org), do: org
def add_all_reports([rep | rest], org) do
case add_report(org, rep) do
^org -> add_all_reports(rest ++ [rep], org)
new_org -> add_all_reports(rest, new_org)
end
end
Easy, right?
No?
Be not afraid
Next steps:
#1: Do small problems.
Use the new patterns
Where to find small problems
 adventofcode.com
 exercism.io
 Exercises for Programmers, by Brian
Hogan
 The Little Schemer, Friedman and Felleisen
#2: Read the Elixir source, and the
source of the better known Elixir libs
#3: Do it again and again. Mix small
problems in with your big projects
#5: Stay in touch!
I am cameronp on:
 twitter
 medium
 github
 gmail
 elixir slack
Lightning Storm: benjaminbenson, on Flickr
Fractal: tommietheturtle, on Flickr
Construction: damienpollet, on Flickr
Photo Credits:
息 2016, Cameron Price
Ad

Recommended

Stop Programming in JavaScript By Luck
Stop Programming in JavaScript By Luck
sergioafp
JavaScript For CSharp Developer
JavaScript For CSharp Developer
Sarvesh Kushwaha
Deep Dive Into Swift
Deep Dive Into Swift
Sarath C
Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtle
Scott Wlaschin
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin
Tdd for BT E2E test community
Tdd for BT E2E test community
Kerry Buckley
Very basic functional design patterns
Very basic functional design patterns
Tomasz Kowal
Write codeforhumans
Write codeforhumans
Narendran R
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
Ruby and Rails by Example (GeekCamp edition)
Ruby and Rails by Example (GeekCamp edition)
bryanbibat
The Joy Of Ruby
The Joy Of Ruby
Clinton Dreisbach
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
Pedro Cunha
3 things you must know to think reactive - Geecon Krak坦w 2015
3 things you must know to think reactive - Geecon Krak坦w 2015
Manuel Bernhardt
Monads in python
Monads in python
eldariof
A Small Talk on Getting Big
A Small Talk on Getting Big
britt
Functions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
Ruby on Rails
Ruby on Rails
bryanbibat
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
Test First Teaching
Test First Teaching
Sarah Allen
Functional programming in ruby
Functional programming in ruby
Koen Handekyn
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
Benjamin Bock
Polymorphism.pptx
Polymorphism.pptx
Vijaykota11
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
error_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnostics
mametter
Testing in the World of Functional Programming
Testing in the World of Functional Programming
Luka Jacobowitz
Introduction to python
Introduction to python
baabtra.com - No. 1 supplier of quality freshers
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
Phoenix for laravel developers
Phoenix for laravel developers
Luiz Messias
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app

More Related Content

Similar to Micropatterns (20)

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
Ruby and Rails by Example (GeekCamp edition)
Ruby and Rails by Example (GeekCamp edition)
bryanbibat
The Joy Of Ruby
The Joy Of Ruby
Clinton Dreisbach
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
Pedro Cunha
3 things you must know to think reactive - Geecon Krak坦w 2015
3 things you must know to think reactive - Geecon Krak坦w 2015
Manuel Bernhardt
Monads in python
Monads in python
eldariof
A Small Talk on Getting Big
A Small Talk on Getting Big
britt
Functions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
Ruby on Rails
Ruby on Rails
bryanbibat
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
Test First Teaching
Test First Teaching
Sarah Allen
Functional programming in ruby
Functional programming in ruby
Koen Handekyn
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
Benjamin Bock
Polymorphism.pptx
Polymorphism.pptx
Vijaykota11
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
error_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnostics
mametter
Testing in the World of Functional Programming
Testing in the World of Functional Programming
Luka Jacobowitz
Introduction to python
Introduction to python
baabtra.com - No. 1 supplier of quality freshers
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
Phoenix for laravel developers
Phoenix for laravel developers
Luiz Messias
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
Ruby and Rails by Example (GeekCamp edition)
Ruby and Rails by Example (GeekCamp edition)
bryanbibat
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
Pedro Cunha
3 things you must know to think reactive - Geecon Krak坦w 2015
3 things you must know to think reactive - Geecon Krak坦w 2015
Manuel Bernhardt
Monads in python
Monads in python
eldariof
A Small Talk on Getting Big
A Small Talk on Getting Big
britt
Functions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
Ruby on Rails
Ruby on Rails
bryanbibat
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
Test First Teaching
Test First Teaching
Sarah Allen
Functional programming in ruby
Functional programming in ruby
Koen Handekyn
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
Benjamin Bock
Polymorphism.pptx
Polymorphism.pptx
Vijaykota11
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
error_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnostics
mametter
Testing in the World of Functional Programming
Testing in the World of Functional Programming
Luka Jacobowitz
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
Phoenix for laravel developers
Phoenix for laravel developers
Luiz Messias

Recently uploaded (20)

Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
grete1122g
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
Best MLM Compensation Plans for Network Marketing Success in 2025
Best MLM Compensation Plans for Network Marketing Success in 2025
LETSCMS Pvt. Ltd.
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
grete1122g
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
Best MLM Compensation Plans for Network Marketing Success in 2025
Best MLM Compensation Plans for Network Marketing Success in 2025
LETSCMS Pvt. Ltd.
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
Ad

Micropatterns