SlideShare une entreprise Scribd logo
1  sur  64
Télécharger pour lire hors ligne
Advanced Design
                  Patterns &
                 Anti-Patterns
                 with Amir Barylko




Amir Barylko                   Advanced Design Patterns
WHO AM I?

  • Software     quality expert

  • Architect

  • Developer

  • Mentor

  • Great      cook

  • The    one who’s entertaining you for the next hour!
Amir Barylko                                          Advanced Design Patterns
RESOURCES

  • Email: amir@barylko.com

  • Twitter: @abarylko

  • Blog: http://www.orthocoders.com

  • Materials: http://www.orthocoders.com/presentations




Amir Barylko                                      Advanced Design Patterns
PATTERNS
                    What are they?
                What are anti-patterns?
               Which patterns do you use?




Amir Barylko                                Advanced Design Patterns
WHAT ARE PATTERNS?

  •Software         design Recipe
  •or     Solution
  •Should         be reusable
  •Should         be general
  •No          particular language
Amir Barylko                         Advanced Design Patterns
ANTI-PATTERNS
  •   More patterns != better design

  •   No cookie cutter

  •   Anti Patterns : Patterns to identify failure

      •   God Classes

      •   High Coupling

      •   Breaking SOLID principles....

      •   (name some)
Amir Barylko                                         Advanced Design Patterns
WHICH PATTERNS
                   DO YOU USE?
  • Fill   here with your patterns:




Amir Barylko                          Advanced Design Patterns
ADVANCED PATTERNS
                     Let’s vote!




Amir Barylko                       Advanced Design Patterns
SOME PATTERNS...

  • MVVM                  • Event Aggregator   • Factory

  • Chain      of resp.   • Event   Sourcing   • Strategy

  • Proxy                 • Test   Factory     • DTO

  • ActiveRecord          • Visitor            • Page   Object

  • Repository            • Null   Object


Amir Barylko                                        Advanced Design Patterns
MODEL VIEW VIEW MODEL

  • Separate      presentation from business logic (view from model)

  • Around       the family of MVC, MVP, etc...

  • Most       useful when binding is available

  • Many       JS libraries uses it (Knockout.js, Ember.js, etc...)

  • WPF        it is based on MVVM


Amir Barylko                                                   Advanced Design Patterns
THE MODEL

  • Represents     data

  • Could      be a one or multiple objects

  • Feeds      the view model

  • However, does      not know the view or the view model




Amir Barylko                                         Advanced Design Patterns
THE VIEW

  • Represents     what is shown to the user

  • Desktop      window

  • HTML       Page

  • Does       not know the model

  • Loosely     coupled to the the view model, binding does all the
    job

Amir Barylko                                           Advanced Design Patterns
THE VIEW MODEL

  • Represents    all the data that the view needs

  • It   could be constructed based on on multiple models

  • Communicate      events to update the view using binding

  • Complex     UI may require composition of MVVM




Amir Barylko                                          Advanced Design Patterns
WHAT IS BINDING?

  • Binding      connects a model and a UI that represents that model

  • In   order to update the UI and the model to match

  • Native      to the framework or library

  • Very       related to Subject and Observer

  • Also       could be an MVC implementation


Amir Barylko                                           Advanced Design Patterns
FOR EACH BINDING
  function AppViewModel() {
      var self = this;

        self.people
            { name:
                      = ko.observableArray([
                      'Bert' },
                                                                      ViewModel
            { name:   'Charles' },
            { name:   'Denise' }
        ]);

        self.addPerson = function() {
            self.people.push({ name: "New at " + new Date() });
        };

        self.removePerson = function() {
            self.people.remove(this);
        }
  }

                      http://knockoutjs.com/documentation/foreach-binding.html


Amir Barylko                                                                     Advanced Design Patterns
FOR EACH BINDING
                                          List binding
 <h4>People</h4>
 <ul data-bind="foreach: people">
   <li>
        Name at position <span data-bind="text: $index"> </span>:
        <span data-bind="text: name"> </span>
        <a href="#" data-bind="click: $parent.removePerson">Remove</a>
     </li>
 </ul>
                                                     Data binding
 <button data-bind="click: addPerson">Add</button>


                               Command binding



Amir Barylko                                          Advanced Design Patterns
THE MAGIC
     ko.applyBindings(new AppViewModel());

                ViewModel              View

               Adding element        Adds <li>

               Remove element     Removes <li>

               Execute function   Click <button>


Amir Barylko                             Advanced Design Patterns
CHAIN OF RESPONSIBILITY

  • More   than one object may handle a request, and the handler
    isn't known a priori.

  • The    handler should be ascertained automatically.

  • You want to issue request to one of several objects without
    specifying The receiver explicitly.

  • The set of objects that can handle a request should be
    specified dynamically

Amir Barylko                                          Advanced Design Patterns
Amir Barylko   Advanced Design Patterns
SnapToX



                  Next
                         SnapToY



                                   SnapToPrevious
                            Next




Amir Barylko                             Advanced Design Patterns
Amir Barylko   Advanced Design Patterns
PROXY

  • Avoid       creating the object until needed

  • Provides      a placeholder for additional functionality

  • Very       useful for mocking

  • Many       implementations exist (IoC, Dynamic proxies, etc)




Amir Barylko                                               Advanced Design Patterns
GOF




Amir Barylko         Advanced Design Patterns
PROXY SEQUENCE




Amir Barylko                Advanced Design Patterns
ACTIVERECORD

  • Isa Domain Model where classes match very closely the
    database structure

  • Each table is mapped to class with methods for finding,
    update, delete, etc.

  • Each       attribute is mapped to a column

  • Associations      are deduced from the classes


Amir Barylko                                         Advanced Design Patterns
create_table   "movies", :force => true do |t|
    t.string     "title"
    t.string     "description"
    t.datetime   "created_at"
    t.datetime   "updated_at"
  end

  create_table   "reviews", :force => true do |t|
    t.string     "name"
    t.integer    "stars"
    t.text       "comment"
    t.integer    "movie_id"
    t.datetime   "created_at"
    t.datetime   "updated_at"
  end

   class Movie < ActiveRecord::Base
     validates_presence_of :title, :description
     has_many :reviews
   end
   class Review < ActiveRecord::Base
     belongs_to :movie
   end


Amir Barylko                                        Advanced Design Patterns
movie = Movie.new

   movie.all # all records

   # filter by title
   movie.where(title: 'Spaceballs')

   # finds by attribute
   movie.find_by_title('Blazing Saddles')

   # order, skip some and limit the result
   movie.order('title DESC').skip(2).limit(5)

   # associations CRUD
   movie.reviews.create(name: 'Jay Sherman',
                   stars: 1,
                   comment: 'It stinks!')


Amir Barylko                                Advanced Design Patterns
REPOSITORY

  • Mediator        between domain and storage

  • Acts       like a collection of items

  • Supports        queries

  • Abstraction       of the storage




Amir Barylko                                     Advanced Design Patterns
Amir Barylko   Advanced Design Patterns
http://martinfowler.com/eaaCatalog/repository.html
Amir Barylko                                     Advanced Design Patterns
ANTIPATTERN
         CHEAPER BY THE DOZEN




Amir Barylko             Advanced Design Patterns
WHAT TO DO?

  • Use    a criteria or better a queryable result (LINQ)

  • Use    a factory to return repositories

  • Use    a UnitOfWork with a factory




Amir Barylko                                        Advanced Design Patterns
EVENT AGGREGATOR
  • Manage      events using a subscribe / publish mechanism

  • Isolates   subscribers from publishers

  • Decouple      events from actual models

  • Events     can be distributed

  • Centralize    event registration logic

  • No    need to track multiple objects


Amir Barylko                                           Advanced Design Patterns
Channel events
  from multiple
  objects into a
  single object to
  s i m p l i f y
  registration for
  clients



Amir Barylko         Advanced Design Patterns
MT COMMONS




Amir Barylko                Advanced Design Patterns
COUPLED




Amir Barylko             Advanced Design Patterns
DECOUPLED




Amir Barylko               Advanced Design Patterns
EVENT SOURCING

  • Register     all changes in the application using events

  • Event      should be persisted

  • Complete       Rebuild

  • Temporal      Query

  • Event      Replay


Amir Barylko                                              Advanced Design Patterns
http://martinfowler.com/eaaDev/EventSourcing.html
Amir Barylko                                    Advanced Design Patterns
Amir Barylko   Advanced Design Patterns
LIST COMPREHENSION

  • Syntax      Construct in languages

  • Describe      properties for the list (sequence)

  • Filter

  • Mapping

  • Same       idea for Set or Dictionary comprehension


Amir Barylko                                              Advanced Design Patterns
LANGUAGE COMPARISON
  • Scala
   for (x <- Stream.from(0); if x*x > 3) yield 2*x

  • LINQ
   var range = Enumerable.Range(0..20);
   from num in range where num * num > 3 select num * 2;

  • Clojure
   (take 20 (for [x (iterate inc 0) :when (> (* x x) 3)] (* 2 x)))


  • Ruby
   (1..20).select { |x| x * x > 3 }.map { |x| x * 2 }


Amir Barylko                                          Advanced Design Patterns
TEST FACTORY / BUILDER

  • Creates     an object for testing (or other) purposes

  • Assumes      defaults

  • Easy   to configure

  • Fluent     interface

  • Usually    has methods to to easily manipulate the domain


Amir Barylko                                            Advanced Design Patterns
public class When_adding_a_an_invalid_extra_frame
   {
       [Test]
       public void Should_throw_an_exception()
       {
           // arrange
           10.Times(() => this.GameBuilder.AddFrame(5, 4));

               var game = this.GameBuilder.Build();

               // act & assert
               new Action(() => game.Roll(8)).Should().Throw();
         }
   }




               http://orthocoders.com/2011/09/05/the-bowling-game-kata-first-attempt/


Amir Barylko                                                                Advanced Design Patterns
Amir Barylko   Advanced Design Patterns
VISITOR

  • Ability    to traverse (visit) a object structure

  • Different     visitors may produce different results

  • Avoid      littering the classes with particular operations




Amir Barylko                                               Advanced Design Patterns
LINQ EXPRESSION TREE




Amir Barylko                    Advanced Design Patterns
EXPRESSION VISITOR




Amir Barylko                   Advanced Design Patterns
AND EXPR EVALUATION




Amir Barylko               Advanced Design Patterns
NULL OBJECT

  • Represent “null” with      an actual instance

  • Provides      default functionality

  • Clear      semantics of “null” for that domain




Amir Barylko                                         Advanced Design Patterns
class animal {
    public:
       virtual void make_sound() = 0;
    };

    class dog : public animal {
       void make_sound() { cout << "woof!" << endl; }
    };

    class null_animal : public animal {
       void make_sound() { }
    };




           http://en.wikipedia.org/wiki/Null_Object_pattern


Amir Barylko                                      Advanced Design Patterns
FACTORY

  • Creates      instances by request

  • More       flexible than Singleton

  • Can    be configured to create different families of objects

  • IoC    containers are closely related

  • Can    be implemented dynamic based on interfaces

  • Can    be used also to release “resource” when not needed
Amir Barylko                                           Advanced Design Patterns
interface GUIFactory {
       public Button createButton();
   }

   class WinFactory implements GUIFactory {
       public Button createButton() {
           return new WinButton();
       }
   }
   class OSXFactory implements GUIFactory {
       public Button createButton() {
           return new OSXButton();
       }
   }

   interface Button {
       public void paint();
   }
      http://en.wikipedia.org/wiki/Abstract_factory_pattern

Amir Barylko                                    Advanced Design Patterns
STRATEGY

  • Abstracts   the algorithm to solve a particular problem

  • Can    be configured dynamically

  • Are    interchangeable




Amir Barylko                                          Advanced Design Patterns
http://orthocoders.com/2010/04/
Amir Barylko                                     Advanced Design Patterns
DATA TRANSFER OBJECT

  • Simplifies   information transfer across services

  • Can    be optimized

  • Easy   to understand




Amir Barylko                                           Advanced Design Patterns
http://martinfowler.com/eaaCatalog/dataTransferObject.html

Amir Barylko                                 Advanced Design Patterns
PAGE OBJECT

  • Abstract      web pages functionality to be used usually in testing

  • Each       page can be reused

  • Changes       in the page impact only the implementation, not the
    clients




Amir Barylko                                              Advanced Design Patterns
class ProjectListPage
       include PageObject

         def navigate
           visit('/projects')
           self
         end

         def edit(project)
           row = find(:xpath, "//td[.='#{project.name}']")
           row.parent.click_link('Edit')
           ProjectEditPage.new
         end

         def projects
           all(:css, "#projects tr")......
         end
   end



Amir Barylko                                     Advanced Design Patterns
When /^I go to the projects page$/ do
       project_list_page.navigate
     end

     When /^I activate the project$/ do
       project_list_page.
         navigate.
         edit(current_project).
         activate.
         save
     end




Amir Barylko                          Advanced Design Patterns
QUESTIONS?




Amir Barylko                Advanced Design Patterns
RESOURCES

  • Email: amir@barylko.com, @abarylko

  • Slides: http://www.orthocoders.com/presentations

  • Patterns: Each   pattern example has a link




Amir Barylko                                      Advanced Design Patterns
RESOURCES II




Amir Barylko                  Advanced Design Patterns
RESOURCES III




Amir Barylko                   Advanced Design Patterns

Contenu connexe

En vedette

PHP Avanzado: Patrones de diseño
PHP Avanzado: Patrones de diseñoPHP Avanzado: Patrones de diseño
PHP Avanzado: Patrones de diseñoRightster
 
Recommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software DevelopmentRecommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software DevelopmentFrancis Palma
 
Unity - Software Design Patterns
Unity - Software Design PatternsUnity - Software Design Patterns
Unity - Software Design PatternsDavid Baron
 
Implementing advanced integration patterns with WSO2 ESB
Implementing advanced integration patterns with WSO2 ESBImplementing advanced integration patterns with WSO2 ESB
Implementing advanced integration patterns with WSO2 ESBWSO2
 
Software Design Patterns in Practice
Software Design Patterns in PracticeSoftware Design Patterns in Practice
Software Design Patterns in PracticePtidej Team
 
Advanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriterAdvanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriterWeaveworks
 
PHP Avanzado: Seguridad Web
PHP Avanzado: Seguridad WebPHP Avanzado: Seguridad Web
PHP Avanzado: Seguridad WebRightster
 
Example for SDS document in Software engineering
Example for SDS document in Software engineeringExample for SDS document in Software engineering
Example for SDS document in Software engineeringRavi Yasas
 
Cuaderno de-ejercicios-y-practicas-php
Cuaderno de-ejercicios-y-practicas-phpCuaderno de-ejercicios-y-practicas-php
Cuaderno de-ejercicios-y-practicas-phplgcj1989
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
Buenas Prácticas de Programación en PHP
Buenas Prácticas de Programación en PHPBuenas Prácticas de Programación en PHP
Buenas Prácticas de Programación en PHPJesus Castagnetto
 

En vedette (14)

PHP Avanzado: Patrones de diseño
PHP Avanzado: Patrones de diseñoPHP Avanzado: Patrones de diseño
PHP Avanzado: Patrones de diseño
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Recommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software DevelopmentRecommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software Development
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Unity - Software Design Patterns
Unity - Software Design PatternsUnity - Software Design Patterns
Unity - Software Design Patterns
 
Implementing advanced integration patterns with WSO2 ESB
Implementing advanced integration patterns with WSO2 ESBImplementing advanced integration patterns with WSO2 ESB
Implementing advanced integration patterns with WSO2 ESB
 
Software Design Patterns in Practice
Software Design Patterns in PracticeSoftware Design Patterns in Practice
Software Design Patterns in Practice
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Advanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriterAdvanced Patterns with io.ReadWriter
Advanced Patterns with io.ReadWriter
 
PHP Avanzado: Seguridad Web
PHP Avanzado: Seguridad WebPHP Avanzado: Seguridad Web
PHP Avanzado: Seguridad Web
 
Example for SDS document in Software engineering
Example for SDS document in Software engineeringExample for SDS document in Software engineering
Example for SDS document in Software engineering
 
Cuaderno de-ejercicios-y-practicas-php
Cuaderno de-ejercicios-y-practicas-phpCuaderno de-ejercicios-y-practicas-php
Cuaderno de-ejercicios-y-practicas-php
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Buenas Prácticas de Programación en PHP
Buenas Prácticas de Programación en PHPBuenas Prácticas de Programación en PHP
Buenas Prácticas de Programación en PHP
 

Similaire à PRDC12 advanced design patterns

sdec11-Advanced-design-patterns
sdec11-Advanced-design-patternssdec11-Advanced-design-patterns
sdec11-Advanced-design-patternsAmir Barylko
 
Rich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptRich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptAmir Barylko
 
Codestrong 2012 breakout session how to develop your own modules
Codestrong 2012 breakout session   how to develop your own modulesCodestrong 2012 breakout session   how to develop your own modules
Codestrong 2012 breakout session how to develop your own modulesAxway Appcelerator
 
Introduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumIntroduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumAaron Saunders
 
Page objects pattern
Page objects patternPage objects pattern
Page objects patternAmir Barylko
 
Page-objects-pattern
Page-objects-patternPage-objects-pattern
Page-objects-patternAmir Barylko
 
Open source libraries and tools
Open source libraries and toolsOpen source libraries and tools
Open source libraries and toolsAmir Barylko
 
PLAT-20 Building Alfresco Prototypes in a Few Hours
PLAT-20 Building Alfresco Prototypes in a Few HoursPLAT-20 Building Alfresco Prototypes in a Few Hours
PLAT-20 Building Alfresco Prototypes in a Few HoursAlfresco Software
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingLearnNowOnline
 
Sitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helixSitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helixPeter Nazarov
 
Single Page Application Development with backbone.js and Simple.Web
Single Page Application Development with backbone.js and Simple.WebSingle Page Application Development with backbone.js and Simple.Web
Single Page Application Development with backbone.js and Simple.WebChris Canal
 
Jumpstart Django
Jumpstart DjangoJumpstart Django
Jumpstart Djangoryates
 
2011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 52011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 5Daniel Fisher
 
Maximizing Code Reuse Across Screens
Maximizing Code Reuse Across ScreensMaximizing Code Reuse Across Screens
Maximizing Code Reuse Across ScreensJason Hanson
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2Julie Iskander
 
Become a Full Stack Web Developer (.NET) - Thisiswali
Become a Full Stack Web Developer (.NET) - ThisiswaliBecome a Full Stack Web Developer (.NET) - Thisiswali
Become a Full Stack Web Developer (.NET) - Thisiswalithisiswali
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016Alex Theedom
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design PatternsAlex Theedom
 
SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"Inhacking
 

Similaire à PRDC12 advanced design patterns (20)

sdec11-Advanced-design-patterns
sdec11-Advanced-design-patternssdec11-Advanced-design-patterns
sdec11-Advanced-design-patterns
 
Rich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptRich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; Coffeescript
 
Codestrong 2012 breakout session how to develop your own modules
Codestrong 2012 breakout session   how to develop your own modulesCodestrong 2012 breakout session   how to develop your own modules
Codestrong 2012 breakout session how to develop your own modules
 
Introduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumIntroduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator Titanium
 
Page objects pattern
Page objects patternPage objects pattern
Page objects pattern
 
Page-objects-pattern
Page-objects-patternPage-objects-pattern
Page-objects-pattern
 
Open source libraries and tools
Open source libraries and toolsOpen source libraries and tools
Open source libraries and tools
 
PLAT-20 Building Alfresco Prototypes in a Few Hours
PLAT-20 Building Alfresco Prototypes in a Few HoursPLAT-20 Building Alfresco Prototypes in a Few Hours
PLAT-20 Building Alfresco Prototypes in a Few Hours
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programming
 
Sitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helixSitecore development approach evolution – destination helix
Sitecore development approach evolution – destination helix
 
Single Page Application Development with backbone.js and Simple.Web
Single Page Application Development with backbone.js and Simple.WebSingle Page Application Development with backbone.js and Simple.Web
Single Page Application Development with backbone.js and Simple.Web
 
Jumpstart Django
Jumpstart DjangoJumpstart Django
Jumpstart Django
 
2011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 52011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 5
 
Maximizing Code Reuse Across Screens
Maximizing Code Reuse Across ScreensMaximizing Code Reuse Across Screens
Maximizing Code Reuse Across Screens
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2
 
Become a Full Stack Web Developer (.NET) - Thisiswali
Become a Full Stack Web Developer (.NET) - ThisiswaliBecome a Full Stack Web Developer (.NET) - Thisiswali
Become a Full Stack Web Developer (.NET) - Thisiswali
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
 
SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 

Plus de Amir Barylko

Functional converter project
Functional converter projectFunctional converter project
Functional converter projectAmir Barylko
 
Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web developmentAmir Barylko
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep diveAmir Barylko
 
Coderetreat hosting training
Coderetreat hosting trainingCoderetreat hosting training
Coderetreat hosting trainingAmir Barylko
 
There's no charge for (functional) awesomeness
There's no charge for (functional) awesomenessThere's no charge for (functional) awesomeness
There's no charge for (functional) awesomenessAmir Barylko
 
What's new in c# 6
What's new in c# 6What's new in c# 6
What's new in c# 6Amir Barylko
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
 
From coach to owner - What I learned from the other side
From coach to owner - What I learned from the other sideFrom coach to owner - What I learned from the other side
From coach to owner - What I learned from the other sideAmir Barylko
 
Communication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivityCommunication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivityAmir Barylko
 
Acceptance Test Driven Development
Acceptance Test Driven DevelopmentAcceptance Test Driven Development
Acceptance Test Driven DevelopmentAmir Barylko
 
Agile requirements
Agile requirementsAgile requirements
Agile requirementsAmir Barylko
 
Agile teams and responsibilities
Agile teams and responsibilitiesAgile teams and responsibilities
Agile teams and responsibilitiesAmir Barylko
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescriptAmir Barylko
 
Agile requirements
Agile requirementsAgile requirements
Agile requirementsAmir Barylko
 

Plus de Amir Barylko (20)

Functional converter project
Functional converter projectFunctional converter project
Functional converter project
 
Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web development
 
Dot Net Core
Dot Net CoreDot Net Core
Dot Net Core
 
No estimates
No estimatesNo estimates
No estimates
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep dive
 
Coderetreat hosting training
Coderetreat hosting trainingCoderetreat hosting training
Coderetreat hosting training
 
There's no charge for (functional) awesomeness
There's no charge for (functional) awesomenessThere's no charge for (functional) awesomeness
There's no charge for (functional) awesomeness
 
What's new in c# 6
What's new in c# 6What's new in c# 6
What's new in c# 6
 
Productive teams
Productive teamsProductive teams
Productive teams
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
From coach to owner - What I learned from the other side
From coach to owner - What I learned from the other sideFrom coach to owner - What I learned from the other side
From coach to owner - What I learned from the other side
 
Communication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivityCommunication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivity
 
Acceptance Test Driven Development
Acceptance Test Driven DevelopmentAcceptance Test Driven Development
Acceptance Test Driven Development
 
Refactoring
RefactoringRefactoring
Refactoring
 
Agile requirements
Agile requirementsAgile requirements
Agile requirements
 
Agile teams and responsibilities
Agile teams and responsibilitiesAgile teams and responsibilities
Agile teams and responsibilities
 
Refactoring
RefactoringRefactoring
Refactoring
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
 
Sass & bootstrap
Sass & bootstrapSass & bootstrap
Sass & bootstrap
 
Agile requirements
Agile requirementsAgile requirements
Agile requirements
 

PRDC12 advanced design patterns

  • 1. Advanced Design Patterns & Anti-Patterns with Amir Barylko Amir Barylko Advanced Design Patterns
  • 2. WHO AM I? • Software quality expert • Architect • Developer • Mentor • Great cook • The one who’s entertaining you for the next hour! Amir Barylko Advanced Design Patterns
  • 3. RESOURCES • Email: amir@barylko.com • Twitter: @abarylko • Blog: http://www.orthocoders.com • Materials: http://www.orthocoders.com/presentations Amir Barylko Advanced Design Patterns
  • 4. PATTERNS What are they? What are anti-patterns? Which patterns do you use? Amir Barylko Advanced Design Patterns
  • 5. WHAT ARE PATTERNS? •Software design Recipe •or Solution •Should be reusable •Should be general •No particular language Amir Barylko Advanced Design Patterns
  • 6. ANTI-PATTERNS • More patterns != better design • No cookie cutter • Anti Patterns : Patterns to identify failure • God Classes • High Coupling • Breaking SOLID principles.... • (name some) Amir Barylko Advanced Design Patterns
  • 7. WHICH PATTERNS DO YOU USE? • Fill here with your patterns: Amir Barylko Advanced Design Patterns
  • 8. ADVANCED PATTERNS Let’s vote! Amir Barylko Advanced Design Patterns
  • 9. SOME PATTERNS... • MVVM • Event Aggregator • Factory • Chain of resp. • Event Sourcing • Strategy • Proxy • Test Factory • DTO • ActiveRecord • Visitor • Page Object • Repository • Null Object Amir Barylko Advanced Design Patterns
  • 10. MODEL VIEW VIEW MODEL • Separate presentation from business logic (view from model) • Around the family of MVC, MVP, etc... • Most useful when binding is available • Many JS libraries uses it (Knockout.js, Ember.js, etc...) • WPF it is based on MVVM Amir Barylko Advanced Design Patterns
  • 11. THE MODEL • Represents data • Could be a one or multiple objects • Feeds the view model • However, does not know the view or the view model Amir Barylko Advanced Design Patterns
  • 12. THE VIEW • Represents what is shown to the user • Desktop window • HTML Page • Does not know the model • Loosely coupled to the the view model, binding does all the job Amir Barylko Advanced Design Patterns
  • 13. THE VIEW MODEL • Represents all the data that the view needs • It could be constructed based on on multiple models • Communicate events to update the view using binding • Complex UI may require composition of MVVM Amir Barylko Advanced Design Patterns
  • 14. WHAT IS BINDING? • Binding connects a model and a UI that represents that model • In order to update the UI and the model to match • Native to the framework or library • Very related to Subject and Observer • Also could be an MVC implementation Amir Barylko Advanced Design Patterns
  • 15. FOR EACH BINDING function AppViewModel() { var self = this; self.people { name: = ko.observableArray([ 'Bert' }, ViewModel { name: 'Charles' }, { name: 'Denise' } ]); self.addPerson = function() { self.people.push({ name: "New at " + new Date() }); }; self.removePerson = function() { self.people.remove(this); } } http://knockoutjs.com/documentation/foreach-binding.html Amir Barylko Advanced Design Patterns
  • 16. FOR EACH BINDING List binding <h4>People</h4> <ul data-bind="foreach: people"> <li> Name at position <span data-bind="text: $index"> </span>: <span data-bind="text: name"> </span> <a href="#" data-bind="click: $parent.removePerson">Remove</a> </li> </ul> Data binding <button data-bind="click: addPerson">Add</button> Command binding Amir Barylko Advanced Design Patterns
  • 17. THE MAGIC ko.applyBindings(new AppViewModel()); ViewModel View Adding element Adds <li> Remove element Removes <li> Execute function Click <button> Amir Barylko Advanced Design Patterns
  • 18. CHAIN OF RESPONSIBILITY • More than one object may handle a request, and the handler isn't known a priori. • The handler should be ascertained automatically. • You want to issue request to one of several objects without specifying The receiver explicitly. • The set of objects that can handle a request should be specified dynamically Amir Barylko Advanced Design Patterns
  • 19. Amir Barylko Advanced Design Patterns
  • 20. SnapToX Next SnapToY SnapToPrevious Next Amir Barylko Advanced Design Patterns
  • 21. Amir Barylko Advanced Design Patterns
  • 22. PROXY • Avoid creating the object until needed • Provides a placeholder for additional functionality • Very useful for mocking • Many implementations exist (IoC, Dynamic proxies, etc) Amir Barylko Advanced Design Patterns
  • 23. GOF Amir Barylko Advanced Design Patterns
  • 24. PROXY SEQUENCE Amir Barylko Advanced Design Patterns
  • 25. ACTIVERECORD • Isa Domain Model where classes match very closely the database structure • Each table is mapped to class with methods for finding, update, delete, etc. • Each attribute is mapped to a column • Associations are deduced from the classes Amir Barylko Advanced Design Patterns
  • 26. create_table "movies", :force => true do |t| t.string "title" t.string "description" t.datetime "created_at" t.datetime "updated_at" end create_table "reviews", :force => true do |t| t.string "name" t.integer "stars" t.text "comment" t.integer "movie_id" t.datetime "created_at" t.datetime "updated_at" end class Movie < ActiveRecord::Base validates_presence_of :title, :description has_many :reviews end class Review < ActiveRecord::Base belongs_to :movie end Amir Barylko Advanced Design Patterns
  • 27. movie = Movie.new movie.all # all records # filter by title movie.where(title: 'Spaceballs') # finds by attribute movie.find_by_title('Blazing Saddles') # order, skip some and limit the result movie.order('title DESC').skip(2).limit(5) # associations CRUD movie.reviews.create(name: 'Jay Sherman', stars: 1, comment: 'It stinks!') Amir Barylko Advanced Design Patterns
  • 28. REPOSITORY • Mediator between domain and storage • Acts like a collection of items • Supports queries • Abstraction of the storage Amir Barylko Advanced Design Patterns
  • 29. Amir Barylko Advanced Design Patterns
  • 31. ANTIPATTERN CHEAPER BY THE DOZEN Amir Barylko Advanced Design Patterns
  • 32. WHAT TO DO? • Use a criteria or better a queryable result (LINQ) • Use a factory to return repositories • Use a UnitOfWork with a factory Amir Barylko Advanced Design Patterns
  • 33. EVENT AGGREGATOR • Manage events using a subscribe / publish mechanism • Isolates subscribers from publishers • Decouple events from actual models • Events can be distributed • Centralize event registration logic • No need to track multiple objects Amir Barylko Advanced Design Patterns
  • 34. Channel events from multiple objects into a single object to s i m p l i f y registration for clients Amir Barylko Advanced Design Patterns
  • 35. MT COMMONS Amir Barylko Advanced Design Patterns
  • 36. COUPLED Amir Barylko Advanced Design Patterns
  • 37. DECOUPLED Amir Barylko Advanced Design Patterns
  • 38. EVENT SOURCING • Register all changes in the application using events • Event should be persisted • Complete Rebuild • Temporal Query • Event Replay Amir Barylko Advanced Design Patterns
  • 40. Amir Barylko Advanced Design Patterns
  • 41. LIST COMPREHENSION • Syntax Construct in languages • Describe properties for the list (sequence) • Filter • Mapping • Same idea for Set or Dictionary comprehension Amir Barylko Advanced Design Patterns
  • 42. LANGUAGE COMPARISON • Scala for (x <- Stream.from(0); if x*x > 3) yield 2*x • LINQ var range = Enumerable.Range(0..20); from num in range where num * num > 3 select num * 2; • Clojure (take 20 (for [x (iterate inc 0) :when (> (* x x) 3)] (* 2 x))) • Ruby (1..20).select { |x| x * x > 3 }.map { |x| x * 2 } Amir Barylko Advanced Design Patterns
  • 43. TEST FACTORY / BUILDER • Creates an object for testing (or other) purposes • Assumes defaults • Easy to configure • Fluent interface • Usually has methods to to easily manipulate the domain Amir Barylko Advanced Design Patterns
  • 44. public class When_adding_a_an_invalid_extra_frame { [Test] public void Should_throw_an_exception() { // arrange 10.Times(() => this.GameBuilder.AddFrame(5, 4)); var game = this.GameBuilder.Build(); // act & assert new Action(() => game.Roll(8)).Should().Throw(); } } http://orthocoders.com/2011/09/05/the-bowling-game-kata-first-attempt/ Amir Barylko Advanced Design Patterns
  • 45. Amir Barylko Advanced Design Patterns
  • 46. VISITOR • Ability to traverse (visit) a object structure • Different visitors may produce different results • Avoid littering the classes with particular operations Amir Barylko Advanced Design Patterns
  • 47. LINQ EXPRESSION TREE Amir Barylko Advanced Design Patterns
  • 48. EXPRESSION VISITOR Amir Barylko Advanced Design Patterns
  • 49. AND EXPR EVALUATION Amir Barylko Advanced Design Patterns
  • 50. NULL OBJECT • Represent “null” with an actual instance • Provides default functionality • Clear semantics of “null” for that domain Amir Barylko Advanced Design Patterns
  • 51. class animal { public: virtual void make_sound() = 0; }; class dog : public animal { void make_sound() { cout << "woof!" << endl; } }; class null_animal : public animal { void make_sound() { } }; http://en.wikipedia.org/wiki/Null_Object_pattern Amir Barylko Advanced Design Patterns
  • 52. FACTORY • Creates instances by request • More flexible than Singleton • Can be configured to create different families of objects • IoC containers are closely related • Can be implemented dynamic based on interfaces • Can be used also to release “resource” when not needed Amir Barylko Advanced Design Patterns
  • 53. interface GUIFactory { public Button createButton(); } class WinFactory implements GUIFactory { public Button createButton() { return new WinButton(); } } class OSXFactory implements GUIFactory { public Button createButton() { return new OSXButton(); } } interface Button { public void paint(); } http://en.wikipedia.org/wiki/Abstract_factory_pattern Amir Barylko Advanced Design Patterns
  • 54. STRATEGY • Abstracts the algorithm to solve a particular problem • Can be configured dynamically • Are interchangeable Amir Barylko Advanced Design Patterns
  • 56. DATA TRANSFER OBJECT • Simplifies information transfer across services • Can be optimized • Easy to understand Amir Barylko Advanced Design Patterns
  • 58. PAGE OBJECT • Abstract web pages functionality to be used usually in testing • Each page can be reused • Changes in the page impact only the implementation, not the clients Amir Barylko Advanced Design Patterns
  • 59. class ProjectListPage include PageObject def navigate visit('/projects') self end def edit(project) row = find(:xpath, "//td[.='#{project.name}']") row.parent.click_link('Edit') ProjectEditPage.new end def projects all(:css, "#projects tr")...... end end Amir Barylko Advanced Design Patterns
  • 60. When /^I go to the projects page$/ do project_list_page.navigate end When /^I activate the project$/ do project_list_page. navigate. edit(current_project). activate. save end Amir Barylko Advanced Design Patterns
  • 61. QUESTIONS? Amir Barylko Advanced Design Patterns
  • 62. RESOURCES • Email: amir@barylko.com, @abarylko • Slides: http://www.orthocoders.com/presentations • Patterns: Each pattern example has a link Amir Barylko Advanced Design Patterns
  • 63. RESOURCES II Amir Barylko Advanced Design Patterns
  • 64. RESOURCES III Amir Barylko Advanced Design Patterns