SlideShare a Scribd company logo
1 of 29
PRINCIPLES AND PATTERNS
OF
SOFTWARE DESIGN
June 29, 2015
Paulo Sousa
Singleton
Tight coupling
Untestable
Premature optimization
Indescriptive Naming
Duplication
Code smells
Signs that the code is rotten and should be refactored
2
Single Responsibility Principle
Open/Close
Liskov Substitution Principle
Interface Segregation
Dependency Inversion
Single Responsibility Principle
A class should have only one reason to change.
4
5
Single Responsibility Principle
6
changeName(first, last)
changeAddress(street, zip)
first: string
last:string
street: string
zip: string
email:string
Person
changeName(first, last)
changeAddress(address)
first: string
last:string
email:string
Person
changeAddress(street, zip)
street: string
zip: string
Address
The domain, SRP and Value Objects
Primitive types are not the best option to represent
domain concepts!
Favour imutability of your objects.
7
Person
«value»
Name
«value»
Address
«value»
NIF
«value»
PhoneNumber
1..*1
1 *
«value»
Email
*
Open/Close Principle
A module should be open for extension but closed for
modification.
8
What would you choose to protect yourself from the
sun?
• Brain surgery to implant sun-resisting hair and
skin, or
• Put on a hat?
9
Polymorphism
10
Template Method
Define an overall
algorithm structure while
allowing for certain
operations (steps) to be
tailored for concrete
cases
11
Strategy
Provide different implementations of the same
algorithm and allow the client to choose which one to
use.
source: Design Patterns: Elements of Reusable Object-Oriented Software
Decorator
Dynamically attach additional
responsibilities to an object.
Decorators provide a flexible
alternative to subclassing for
extending functionality.
source: Design Patterns: Elements of Reusable
Object-Oriented Software
Visitor
Separate the algorithm from
the data structure it operates
on by creating a visitor that
traverses the desired object.
Source: http://www.oodesign.com/visitor-pattern.html
Liskov Substitution Principle
Subclasses should be substitutable for their base
classes.
15
The implication is:
Subclasses must abide the
same contract and invariants
of the base class, without
semantic changes.
The circle/elipse dilemma
16
The circle/ellipse dilemma
17
Interface Seggregation Principle
Many client specific interfaces are better than one
general purpose interface.
18
Interface Seggregation Principle
19
Interface Seggregation Principle
20
Dependency Inversion Principle
Depend upon Abstractions. Do not depend upon
concretions.
21
Dependency Inversion Principle
22
Dependency Injection
Modules declare their dependencies but do not
create them explicitily
23
class Component {
NeededService svc;
Component() {
svc = new ServiceImplementation();
}
}
class Component {
NeededService svc;
Component(NeededService impl) {
svc = impl;
}
}
Separated Interface
Defines an interface in a
separate package from
its implementation.
source: Patterns of Enterprise Application Architecture
Closings
25
Key Principles
 Consider what should be variable in your design
 Program to an interface not an implementation
 Keep different responsibilities apart from each
other
 Favour composition instead of inheritance
References
Bibliography
• Robert C. Martin. Design Principles and Design
Patterns.
http://www.objectmentor.com/resources/articles/Princ
iples_and_Patterns.pdf
• William Durand. From STUPID to SOLID code!.
http://williamdurand.fr/2013/07/30/from-stupid-to-
solid-code/
• Allen Holub. Why extends is evil.
http://www.javaworld.com/javaworld/jw-08-2003/jw-
0801-toolbox.html
• Erich Gamma, Richard Helm, Ralph Johnson, John
Vissides. Design patterns : elements of reusable object-
oriented software. Adisson-Wesley.

More Related Content

What's hot

SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design PrinciplesAndreas Enbohm
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET CoreAvanade Nederland
 
Solid principles
Solid principlesSolid principles
Solid principlesToan Nguyen
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#Aditya Kumar Rajan
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility PrincipleBADR
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignYoung-Ho Cho
 
[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台
[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台
[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台Shengyou Fan
 

What's hot (20)

SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 
Solid principles
Solid principlesSolid principles
Solid principles
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
 
Solid principles
Solid principlesSolid principles
Solid principles
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
React workshop
React workshopReact workshop
React workshop
 
React
React React
React
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring boot
Spring bootSpring boot
Spring boot
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台
[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台
[MOPCON 2022] 以 Kotlin Multiplatform 制霸全平台
 

Viewers also liked (15)

Rest web services
Rest web servicesRest web services
Rest web services
 
PoEAA by Example
PoEAA by ExamplePoEAA by Example
PoEAA by Example
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 
Lição prova professor coordenador
Lição prova professor coordenadorLição prova professor coordenador
Lição prova professor coordenador
 
REST beyond CRUD
REST beyond CRUDREST beyond CRUD
REST beyond CRUD
 
Principles of Service Orientation
Principles of Service OrientationPrinciples of Service Orientation
Principles of Service Orientation
 
Modern web architectural patterns
Modern web architectural patternsModern web architectural patterns
Modern web architectural patterns
 
Patterns for distributed systems
Patterns for distributed systemsPatterns for distributed systems
Patterns for distributed systems
 
Communication
CommunicationCommunication
Communication
 
RESTful services Design Lab
RESTful services Design LabRESTful services Design Lab
RESTful services Design Lab
 
Decoupled Communication
Decoupled CommunicationDecoupled Communication
Decoupled Communication
 
OO design principles and patterns
OO design principles and patternsOO design principles and patterns
OO design principles and patterns
 
Benefits of Hypermedia API
Benefits of Hypermedia APIBenefits of Hypermedia API
Benefits of Hypermedia API
 
Software Product Lines
Software Product LinesSoftware Product Lines
Software Product Lines
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)
 

Similar to Design Patterns: From STUPID to SOLID code

Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
SOLID principles-Present
SOLID principles-PresentSOLID principles-Present
SOLID principles-PresentQuang Nguyen
 
Design principle vs design patterns
Design principle vs design patternsDesign principle vs design patterns
Design principle vs design patternsPrabhakar Sharma
 
Development principles in test automation!
Development principles in test automation!Development principles in test automation!
Development principles in test automation!David Baak
 
OO design principles & heuristics
OO design principles & heuristicsOO design principles & heuristics
OO design principles & heuristicsDhaval Shah
 
Inversion of Control
Inversion of ControlInversion of Control
Inversion of ControlShuhab Tariq
 
Is your code solid
Is your code solidIs your code solid
Is your code solidNathan Gloyn
 
Common Design Patterns.pptx
Common Design Patterns.pptxCommon Design Patterns.pptx
Common Design Patterns.pptxfake195786
 
Solid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSolid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSimon Gould
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Hammad Rajjoub
 
The software design principles
The software design principlesThe software design principles
The software design principlesAman Kesarwani
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
Software Design Principles (SOLID)
Software Design Principles (SOLID)Software Design Principles (SOLID)
Software Design Principles (SOLID)ASIMYILDIZ
 

Similar to Design Patterns: From STUPID to SOLID code (20)

Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
SOLID principles-Present
SOLID principles-PresentSOLID principles-Present
SOLID principles-Present
 
OO Design Principles
OO Design PrinciplesOO Design Principles
OO Design Principles
 
Design principle vs design patterns
Design principle vs design patternsDesign principle vs design patterns
Design principle vs design patterns
 
Development principles in test automation!
Development principles in test automation!Development principles in test automation!
Development principles in test automation!
 
L07 Design Principles
L07 Design PrinciplesL07 Design Principles
L07 Design Principles
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
OO design principles & heuristics
OO design principles & heuristicsOO design principles & heuristics
OO design principles & heuristics
 
Inversion of Control
Inversion of ControlInversion of Control
Inversion of Control
 
Is your code solid
Is your code solidIs your code solid
Is your code solid
 
Solid
SolidSolid
Solid
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
Common Design Patterns.pptx
Common Design Patterns.pptxCommon Design Patterns.pptx
Common Design Patterns.pptx
 
Solid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSolid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile development
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-
 
The software design principles
The software design principlesThe software design principles
The software design principles
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Software Design Principles (SOLID)
Software Design Principles (SOLID)Software Design Principles (SOLID)
Software Design Principles (SOLID)
 

More from Paulo Gandra de Sousa

More from Paulo Gandra de Sousa (9)

Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
Minds-on DDD
Minds-on DDDMinds-on DDD
Minds-on DDD
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Design Patterns: Back to Basics
Design Patterns: Back to BasicsDesign Patterns: Back to Basics
Design Patterns: Back to Basics
 
Hypermedia APIs
Hypermedia APIsHypermedia APIs
Hypermedia APIs
 
Revision control with Mercurial
Revision control with MercurialRevision control with Mercurial
Revision control with Mercurial
 
Documenting Software Architectures
Documenting Software ArchitecturesDocumenting Software Architectures
Documenting Software Architectures
 
models of distributed computing
models of distributed computingmodels of distributed computing
models of distributed computing
 
Distributed Systems
Distributed SystemsDistributed Systems
Distributed Systems
 

Recently uploaded

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Recently uploaded (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Design Patterns: From STUPID to SOLID code

Editor's Notes

  1. Tight coupling: criar objetos concretos dentro de métodos faz a classe ficar dependente  Dependency injection
  2. Uma classe deve ter uma e apenas uma responsabilidade Favorecer classes “pequenas” focadas num único aspeto/conceito do problema Todos os métodos da interface pública da classe devem fazer um conjunto coerente Permite melhor divisão de tarefas e maior facilidade de manutenção
  3. Uma classe deve ser aberta (open) para extensão mas fechada (close) para modificação Novos requisitos e comportamentos devem ser obtidos através da extensão da classe e não da sua modificação Ao criar a classe identificar (possíveis) pontos de futura variabilidade e desenhar a classe para poder ser estendida nesses pontos Template Method Strategy Decorator – veremos mais tarde Visitor – veremos mais tarde
  4. Don’t touch existing code (bug fixes excluded). You should have no reason to change the internals of a class to add new behaviour, instead you should extend the class with the new behaviour.
  5. Problema: Permitir que o cliente escolha de muitas alternativas, complexas, sendo que não se deseja incluir código para todas. Solução: Fazer muitas implementações da mesma interface, e permitir que o cliente seleccione uma e a devolva. Definir uma família de algoritmos, encapsular cada um deles, e torná-los permutáveis. Strategy permite que o algoritmo varie independentemente dos clientes que o usam.
  6. Problem: Allow functionally to be layered around an abstraction, but still dynamically changeable. Solution: Combine inheritance and composition. By making an object that both subclasses from anther class and holds an instance of the class, can add new behavior while referring all other behavior to the original class.
  7. Problem How to dinamically add new operations to existing data structures? Solution Separate the algorithm from the data structure it operates on by creating a visitor that traverses the desired object. the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle. In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.
  8. Qualquer método que espere um objeto de um tipo A deve poder trabalhar com qualquer objeto derivado de A Classes derivadas devem cumprir o mesmo contrato (sem alterações semânticas) da classe base
  9. Muitas interfaces específicas são melhores que uma única genérica Classes clientes não devem ser forçadas a depender de interfaces que não necessitam (não usam)
  10. Deve depender-se de abstrações e não de concretizações Ex., List vs. ArrayList Criar uma camada de abstração que diminuirá o acoplamento entre módulos Abstrações tendem a modificar com menos frequência que as concretizações
  11. Clients should depend on abstractions, not concretions. I.e., program to an interface not a realization. DIP Deve depender-se de abstrações e não de concretizações Ex., List vs. ArrayList Criar uma camada de abstração que diminuirá o acoplamento entre módulos
  12. Problema: Como diminuir o acoplamento entre classes de camadas diferentes Solução: Colocar a interface do serviço num package e a implementação noutro Diminui o coupling entre classes do sistema evitando que classes de uma camada façam referência directa a outra Ex., componentes de lógica de acesso a dados chamarem métodos de classes de negócio
  13. Program to an interface not an implementation: Decreases coupling/dependencies among classes Favour composition instead of inheritance: Don’t inherit behaviour you don’t need. Allow for implementation changes Consider what should be variable in your design: hide what varies and allow for substitution via common interface Keep different responsibilities apart from each other: Don’t create big, fat classes Program to an interface and not to an implementation - Purring this more succinctly, you should define the top of any class hierarchy with an abstract class, which implements no methods, but simply defines the methods that class will support. Then, in all of your derived classes you have more freedom to implement these methods as most suits your purposes. Essentially this means considering the object you are dealing with as a black box. Do not consider how it does its tasks, just consider the interface (set of public methods) that it allows you to use. Favor object composition over inheritance - While many beginning OO programmers use inheritance to solve every problem when an alternative way is needed to accomplish something. This works well for handling one variation. However, if something else starts to vary you get an exponentially increasing number of possible combinations. Using inheritance alone requires a correspondingly large number of classes (one for each combination). As you begin to write more elaborate programs, the merits of object composition become apparent. Your new object can have the interface that is best for what you want to accomplish without having all the methods of the parent classes.  Consider what should be variable in your design - Focus on encapsulating the concept that varies. Allow substitution of variable implementations via a common interface.