Upload
barry-o-sullivan
View
355
Download
1
Embed Size (px)
Citation preview
Design PatternsThe Good, the Bad, and the Anti-Pattern
Barry O Sullivan 2016
Who am me?
My name is Barry O Sullivan @barryosull
- Product Developer - Systems Architect - Development Manager - Freelancer
Current positionFinishing up as Development Manager for Hiup(Going to back to contracting, shhhhh)
What is a Design pattern?
A design pattern is a general, repeatable solution to a commonly occurring problem in
software design
What does this mean?
It means we can design our systems to support change, rather than fight it.
It’s about expressing your intent
• Changes become easier• Less hacks• Code is easier to read and understand• Faster development• Fewer bugs
That sounds amazing!
So we should all use them right?
Well there’s a catch
Design patterns make it very easy to do one thing, by making it harder to do others
It’s architecture, which is about tradeoffs
In other words
Using the wrong pattern is worse than using no pattern at all
The Anti-Pattern
Patterns that seem like they’ll work but don’t
Anti-Patterns are usually emergent and are always bad
Ball of Mud
• No discernable architecture
• Everything is different
• Extracting it piece by piece doesn’t work You just end up with mud everywhere.
God Class
And God said “Let’s put all the functionality in the user
class”
Large, bloated classes that do everything and are impossible to understand and maintain.
The Big Reveal
Using the wrong design patternIs an Anti-Pattern
The Awkward Truth
A ball of mud is better than a system built with all the patterns and zero design
>
Design patterns
The usual suspects
1. Singleton2. Fluent Interface
3. Command4. Observer
5. ActiveRecord6. MVC
Singleton Pattern“There can only be one”
For when there should only be one instance of an object system wide
Singleton PatternWhere to use it?
• Logging• DB connection• Message Bus• Command Handler
$handler= CommandHandler::instance();
try {$handler->handle(
new BeEgyptian($SeanConnery)
);} catch (NobodyIsBuyingItException $e) {
….}
Singleton Pattern
Where not to use it?
• Globally accessing a class(Laravel Facades, I'm looking at you!)
Use DI instead (like the Laravel 5.1 request object)
Fluent Interface
“You talking to me?”
Chain methods together to make complex programs easier to compose and read
$customer->add_to_basket($hat, 1)->add_to_basket($dress, 2)->apply_discount_code(“23453”)->purchase(“4242-4242-4242-4242”, “123”, “12/12”);
Fluent Interface
Where to use it
For representing strongly defined grammars• SQL (eg Eloquent)
• Domain Specific Languages
Fluent Interface
Where to not use it
Anywhere else
If you’re not representing a language, don’t use this interface
Main offender, jQuery$(“.elem”).parents(“.main”).find(“input.name”)
.data(“name”,”john”).addClass(“selected”).removeClass(“.meh_class”).val(“what the?”)
Command pattern“Can I take your order sir?”
Encapsulate a command that can be handled now or later.
Contains all the data required to run the command
Command pattern
Where to use it
Anywhere you just want something done and don’t care about the details
(Controller => Application Layer)
Message passing
Scheduled tasks
Command pattern
Where not to use it
Anywhere it gets in the way
You’re creating a wall. Only use it if the wall is useful
Observer PatternDecoupled systems that want to alert each other
of changes
An observer registers itself with a subject. When the subject changes, it alerts the observer
Observer Pattern
Where to use it
Messaging systems
Anywhere that the relationships can change
Modular systems
Observer Pattern
Where not to use it
Where the objects scope will never change Ie, it's created internally, used, then
discarded
Sometimes things should be coupled, and that’s ok
Active Record (ORM)“We're all connected”
Make it easy to store your class hierarchy in a Database, without having to write all the
translation code (eg. to SQL)
$team= NewsTeam::find(‘Evening News Team);
$new_insult = new Insult();$new_insult ->target = ‘Their Clothes’;$new_insult->question =‘Purchase location’;$new_insult ->punchline = ‘The Toilet Store’;
$team->insults[] = $new_insult ;$team->status = ‘rekd’;$team->save();
Active Record (ORM)
Where to use it
Simple CRUD based domains where your objects have simple relational structures
Not a lot of domain behavior
Mostly just key value pairs
Active Record (ORM)
Where not to use it
Complex domains with multiple views on data, rather than just the basic view
Eg. A checkout process that has promotions and special offers based on your address
Anything with lots of analytics
Active RecordAlternatives
The Repository pattern:Keep the domain logic separate from the storage logic
CQRS: Have a single data model, multiple views built from that core model
NoSQL:Worth a mention, store trees of data with dynamic shapes
MVC“Divide and Conquer”
Structure your app into three distinct areas of responsibility, Model/View/Controller
MVC
Where to use it
Any complex application that's more than a single form
You’re most likely already using it at work(If not, I’m feel your pain)
MVCWhere it goes wrong
MVC doesn't explain the M part very well.
M is where Design patterns really come into play
All examples code use ORM, so people think that you just use ORM and your M part is sorted
That's not design, that's laziness. Learn patterns, git gud! (Dark Souls!)
Is it worth it?
Definitely!
Imagine your code as network cables, now imagine going from this to this
=>
Light at the end of the tunnel
A well designed system is a pleasure to change and test
It just takes time and effort to understand the patterns
“You have to get worse, before you can get better”
Choosing the right pattern
Don't just pick one and assume it will be fine
Research them all, understand their shape
Look at the problem, figure out what changes and why it’s hard to change. Find the pattern.
Try to use them and fail (on a branch)
Honourable mentions
• Factory pattern• Repository pattern• Interfaces (just in general)• Dependency injection• Façade• Iterator• Abstract classes
Further Reading
“If I have seen further, it is by standing on the shoulders of giants.”
• http://www.martinfowler.com/• https://sourcemaking.com/• https://en.wikipedia.org/wiki/Software_design_pattern
Also, why not talk to the other developers here?(I’m sure we’ve all fucked up with patterns as much as I have . . . )
Thank you
Any questions?