Xlab #2: wzorce projektowe

Preview:

Citation preview

www.xsolve.plAgile Software House

Design patterns

www.xsolve.plAgile Software House

Goals

1. 10:00 Przywitanie

2. 10:30 Dobre praktyki programowania

3. 11:00 Wzorce projektowe

○ Creational design patterns

○ Structural patterns

○ Behavioral design patterns

4. 12:00 Przerwa na pizzę

5. 12:30 Code Kata - Supermarket

6. 14:00 Analiza rozwiązań

7. 14:30 Podsumowanie

na żywych przykładach wspólnie przygotujemy SOLIDny kod

xlab #2: Wzorce projektowe agenda

www.xsolve.plAgile Software House

www.xsolve.plAgile Software House

Speakers

PHP Software Developer

Tomasz Łysek

www.xsolve.plAgile Software House

Masterzu developerzu i architekturzu dla rozwiązań biznesowych od ok. 10 lat.Woli backend i DB niż elementy frontu. Pilnuje by studenci pisali porządny kod.W wolnym czasie gotuje, bije innych na treningach i relaksuje się przy zmywaniu naczyń.

"Wąż powiedział: choć ze mna pokażę Ci zalety JS-a. (...) Projekt osunął się powoli, jak pada drzewo. Team Leader stłumił nawet odgłos upadku moralnego programisty."Antoine de Saint-Exupéry

Senior PHP Software Developer

Mateusz Rosiek

www.xsolve.plAgile Software House

Backend developer PHP od 5 lat. Aktualnie zajmuję się aplikacją wystawiającą API RESTowe dla systemu e-commerce.Prywatnie właściciel jeża.

“W nienawiści do JS tak zostałem wychowanyHardcor PHP, ogień PHP”~Paulo Coelho

PHP Software Developer

Ion Bazan

www.xsolve.plAgile Software House

PHP Developer, w XSolve od 9 miesięcy. Aktualnie zajmuje się projektem platformy B2B/B2C dla branży oponiarskiej.

“They told me JS was fun but all I got was promises.” ~Paulo Coelho

PHP Software Developer

Piotr Leśniowski

www.xsolve.plAgile Software House

Jestę developerę. Programuję w PHP i JS w celu zarobkowym od 5 lat a hobbystycznie od 8-ej klasy podstawówki. Romansowałem m. in. z C# i Pythonem, aczkolwiek przygody te nie zakończyły się zdrowym i długotrwałym związkiem. Gdy nie programuję, oddaję się słuchaniu muzyki, kolekcjonowaniu płyt, brawurowej jeździe samochodem marki Cinquecento oraz denerwowaniu się na marne, kinowe adaptacje gier. W młodości chciałem zostać śmieciarzem albo kierowcą rajdowym. Skończyło się na wyłapywaniu śmieci w oprogramowaniu oraz na prawku kat. B. Aktualnie jestem odpowiedzialny za projektowanie i utrzymywanie RESTowego API dla aplikacji SPA.

PS.Lubię placki... i przemyślany kod.

PSS.Czasami coś machnę w Angularze.

www.xsolve.plAgile Software House

Your turn

www.xsolve.plAgile Software House

Contract

● We would like to write SOLID code, so:

○ We need to know and use best practices

○ We need to know and use basic design patterns

○ We need to write tests

● We would like to have fun, eat pizza and drink beers! :)

What we want to achieve

Contract

www.xsolve.plAgile Software House

www.xsolve.plAgile Software House

SOLID

www.xsolve.plAgile Software House

What is it?

www.xsolve.plAgile Software House

“[SOLID] is a mnemonic acronym introduced by Michael Feathers for the "first five principles" named by Robert C. Martin in the early 2000s that stands for five basic principles of object-oriented programming and design”

- Wikipedia

What is it?

www.xsolve.plAgile Software House

www.xsolve.plAgile Software House

● Single responsibility principle

What is it?

www.xsolve.plAgile Software House

● Single responsibility principle

● Open/Closed principle

What is it?

www.xsolve.plAgile Software House

● Single responsibility principle

● Open/Closed principle

● Liskov substitution principle

What is it?

www.xsolve.plAgile Software House

● Single responsibility principle

● Open/Closed principle

● Liskov substitution principle

● Interface segregation principle

What is it?

www.xsolve.plAgile Software House

What is it?

● Single responsibility principle

● Open/Closed principle

● Liskov substitution principle

● Interface segregation principle

● Dependency inversion principle

www.xsolve.plAgile Software House

Does my code stink?

www.xsolve.plAgile Software House

Probably yes.

www.xsolve.plAgile Software House

How do I know if my code stinks?

www.xsolve.plAgile Software House

How do I know if my code stinks?

● Rigidity - design is hard or nearly impossible to change

● Fragility - design is easily breakable

● Solution is non-reusable

● Design makes it nearly impossible to do the right thing

www.xsolve.plAgile Software House

Single responsibility principle

● If something is good for everything then it’s pretty much for nothing

● A class should only have one responsibility

● There shouldn’t be more than one reason for a class to change

● TL;DR - a class should focus on doing one thing and one thing only

www.xsolve.plAgile Software House

Single responsibility principle

www.xsolve.plAgile Software House

Single responsibility principle

www.xsolve.plAgile Software House

Open/closed principle

● A class should be open for extending

● A class should be closed for changes

● TL;DR - when requirements change we should extend the existing code,

not change it

www.xsolve.plAgile Software House

Open/closed principle

www.xsolve.plAgile Software House

Open/closed principle

www.xsolve.plAgile Software House

Liskov substitution principle

● A class implementing an abstraction should do it properly. In a way that

the code that is based on the abstraction should not be dependant on

concrete implementations, but it should allow for substituting different

implementations of formentioned abstraction

● TL;DR - Subclasses should behave properly when substituted for base

class

www.xsolve.plAgile Software House

Liskov substitution principle

www.xsolve.plAgile Software House

Liskov substitution principle

www.xsolve.plAgile Software House

Interface segregation principle

● Many client-specific interfaces are better than one general-purpose

interface

● A class should not be dependant on methods that it doesn’t use

● TL;DR - Avoid fat interfaces

www.xsolve.plAgile Software House

Interface segregation principle

www.xsolve.plAgile Software House

Interface segregation principle

www.xsolve.plAgile Software House

Dependency inversion principle

● A base class should not be dependant on subclass, both should be

dependant on abstraction

● TL;DR - Use interfaces and abstractions

www.xsolve.plAgile Software House

Dependency inversion principle

www.xsolve.plAgile Software House

Law of Demeter

www.xsolve.plAgile Software House

Law of Demeter

● A principle of least knowledge

● A method of an object can call another method of:

○ The same object

○ Any parameter passed to it

○ Any object created by it

○ Direct component of an object to which it belongs

● TL;DR - Don’t talk to strangers

www.xsolve.plAgile Software House

Design Patterns

www.xsolve.plAgile Software House

Creational Design Patterns

www.xsolve.plAgile Software House

Creational design patterns

● They are all about class instantiation

● They can be divided into class and object-creational patterns

● They encapsulate using new keyword to create objects

www.xsolve.plAgile Software House

Can’t we just use constructor?

www.xsolve.plAgile Software House

No.

www.xsolve.plAgile Software House

Abstract Factory

Provide a level of indirection that abstracts the creation of families of related or

dependent objects without directly specifying their concrete classes. The

"factory" object has the responsibility for providing creation services for the

entire platform family. Clients never create platform objects directly, they ask

the factory to do that for them.

www.xsolve.plAgile Software House

Abstract Factory

www.xsolve.plAgile Software House

Abstract Factory

● AbstractPizzaFactory provides a Factory Method for Pizza object.

● CapricciosaPizzaFactory and ProsciuttoPizzaFactory are concrete Pizza

factories extending/implementing AbstractPizzaFactory.

● Client does not have idea which concrete object the factory returns

www.xsolve.plAgile Software House

Abstract Factory

www.xsolve.plAgile Software House

Factory Method

Factory Method is to creating objects as Template Method is to implementing

an algorithm. A superclass specifies all standard and generic behavior (using

pure virtual "placeholders" for creation steps), and then delegates the creation

details to subclasses that are supplied by the client.

www.xsolve.plAgile Software House

Factory Method

www.xsolve.plAgile Software House

Factory Method

● Evaluates arguments and decides which derived object to create and

return

● Defines an interface for creating objects, but lets subclasses decide which

classes to instantiate

www.xsolve.plAgile Software House

Factory Method

www.xsolve.plAgile Software House

Builder

The Builder pattern separates the construction of a complex object from its

representation so that the same construction process can create different

representations. The focus/distinction is on creating complex aggregates.

www.xsolve.plAgile Software House

Builder

www.xsolve.plAgile Software House

Builder

● Separate the construction of a complex object from its representation so that the same construction process can create different representations.

● Parse a complex representation, create one of several targets.

www.xsolve.plAgile Software House

Builder

www.xsolve.plAgile Software House

Builder

www.xsolve.plAgile Software House

Test results

www.xsolve.plAgile Software House

Structural Design Patterns

Private Data Class● The private class data design pattern seeks to reduce exposure of attributes by

limiting their visibility. It reduces the number of class attributes by encapsulating them in single Data object. It allows the class designer to remove write privilege of attributes that are intended to be set only during construction, even from methods of the target class.

Source: wikipedia

● Separates data from business logic.● Encapsulates class data within two objects.● Can be combined with Value Object pattern.

TL;DR: Get fields from your class and put them in separate (new) class.

Flyweight● A flyweight is an object that minimizes memory use by sharing as much data as

possible with other similar objects.Source: wikipedia

● Minimal structure.● Simple interface.● Easy to implement.● Should implement Private Data Class or at least Value Object.

TL;DR: make multiple small classes from your big data business logic class (get the core and put it into different class).

Flyweight

Flyweight

Facade● A facade is an object that provides a simplified interface to a larger body of code,

such as a class library. The Facade design pattern is often used when a system is very complex or difficult to understand because the system has a large number of interdependent classes or its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client.

Source: wikipedia

● Simplify interface of complex class/classes.● Provide new interface for class/classes.

TL;DR: If you have very complex class or subsystem just do one class facade for simply to use interface.

Facade

Facade

Adapter● Allows the interface of an existing class to be used as another interface. An adapter

helps two incompatible interfaces to work together. This is the real world definition for an adapter. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter design pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

Source: wikipedia

● Create brand new interface for an existing class.● Adapt system interface to clients needs.● Best way to create new system with old system interface.

TL;DR: When there is a strong need to adapt created interface to new requirements - make new class with needed methods and run in them the old one’s

AdapterFacade vs Adapter:● Make new interface for existing one,● Adapter uses already created interface,● Facade create new interface from the scratch.

Adapter vs Bridge:● If you use aggregation then make it in abstract and create bridge but if you use

inheritance then make adapter.

Adapter

Proxy● A proxy, in its most general form, is a class functioning as an interface to something

else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes.

Source: wikipedia

● Protects complex and sensitive objects from undesirable calling.● Additional level for control data flow.● Complex Proxy can be use as Service Stub.

TL;DR: If you need to control flow through part of system or service - add class between that part that will be mocking functionality.

Proxy

Decorator● Allows behavior to be added to an individual object, either statically or dynamically,

without affecting the behavior of other objects from the same class.[1] The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.

Source: wikipedia● Adding new functionality to already existing classes without changing code of that

classes.● Recursive wrapping core objects with new functionalities.● Strong SOLID.

TL;DR: If you want to add new features to already existing class - don’t change code of that class but add new class and pass core class instance to it.

Decorator● Proxy vs Decorator: Proxy creates instance of class within own object, Decorator

gets the class instance in constructor.

Composite● Describes that a group of objects is to be treated in the same way as a single

instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly

Source: wikipedia● Manage pool of objects with one objects with same interface.● Creates tree structure.● Solid hierarchy structure in code.● DP Composite ≠ UML Composite

TL;DR: Use it when you need to create collection of one class objects.

Composite

www.xsolve.plAgile Software House

Behavioral Design Patterns

www.xsolve.plAgile Software House

Strategy

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime. The strategy pattern● defines a family of algorithms,● encapsulates each algorithm, and● makes the algorithms interchangeable within that family.

source: wikipedia.com

www.xsolve.plAgile Software House

Strategy

https://github.com/domnikl/DesignPatternsPHP/tree/master/Behavioral/Strategy

www.xsolve.plAgile Software House

Strategy

https://sourcemaking.com/design_patterns/strategy

www.xsolve.plAgile Software House

Strategy

https://sourcemaking.com/design_patterns/strategy

www.xsolve.plAgile Software House

Iterator

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

source: wikipedia.com

www.xsolve.plAgile Software House

Iterator

https://sourcemaking.com/design_patterns/iterator

www.xsolve.plAgile Software House

Iterator

https://sourcemaking.com/design_patterns/iterator

www.xsolve.plAgile Software House

Mediator

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact.With the mediator pattern, communication between objects is encapsulated with a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby lowering the coupling.

source: wikipedia.com

www.xsolve.plAgile Software House

Mediator

www.xsolve.plAgile Software House

Mediator

www.xsolve.plAgile Software House

Mediator

www.xsolve.plAgile Software House

Mediator

www.xsolve.plAgile Software House

Recapitulation

www.xsolve.plAgile Software House

Recapitulation

● What does Solid mean?

● What does Demeter law mean?

● How to work with creational design patterns?

● How to work with structural design patterns?

● How to work with behavioral design patterns?

www.xsolve.plAgile Software House

Recapitulation

www.xsolve.plAgile Software House

xsolve.pl/career

Thank you for your time!

Recommended