SlideShare uma empresa Scribd logo
1 de 119
Baixar para ler offline
Micropatterns
Learning to reach for the right tool
Hi! I’m Cameron
(@cameronp)
Time for a story…
October, 2014
BASIC C
Pascal
C++
PythonJava
Ruby
C#
But it didn’t work this
time…
Time passes…
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
“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 aren’t five
elements in the list?
Well… it’ll crash
Well… it’ll crash
(And maybe that’s 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 we’re ready to
perform validations…
But I’m not going to..
Because there’s 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
Let’s 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
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…
… you’ll find the big architectural
patterns easy to understand
Ok. Let’s 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

Mais conteúdo relacionado

Semelhante a Micropatterns

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
 
Monads in python
Monads in pythonMonads in python
Monads in python
eldariof
 
A Small Talk on Getting Big
A Small Talk on Getting BigA Small Talk on Getting Big
A Small Talk on Getting Big
britt
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
Luiz Messias
 

Semelhante a Micropatterns (20)

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
Ruby and Rails by Example (GeekCamp edition)
Ruby and Rails by Example (GeekCamp edition)Ruby and Rails by Example (GeekCamp edition)
Ruby and Rails by Example (GeekCamp edition)
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 20153 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
 
Monads in python
Monads in pythonMonads in python
Monads in python
 
A Small Talk on Getting Big
A Small Talk on Getting BigA Small Talk on Getting Big
A Small Talk on Getting Big
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
Test First Teaching
Test First TeachingTest First Teaching
Test First Teaching
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
 
error_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnosticserror_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnostics
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
 

Último

%+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
 
%+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
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
+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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Último (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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 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 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...
 
%+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...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
+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...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
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
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
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 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
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

Micropatterns