Professional Documents
Culture Documents
FOUNDATION
Adnan Masood
http://blog.adnanmasood.com
@adnanmasood
adnanmasood@acm.org
Presented at Inland Empire .NET UG
12/11/2012
EXAMPLE APP: BEFORE AND
A FT E R
IMessageInfo
IMessageInfo IEmailSender
IEmailSender
Retriever
Retriever
Email
EmailProcessingService
Sending EmailProcessingService
App
Database
Database
Databas
Databas Reader
Flat Reader
Flat File
File e
e Service
Service
IMessage
IMessage
Info
Info
Retriever
Retriever
File IFileFormat
IFileFormat FileReader
FileReader
XML
XML File
File Reader Service
Reader Service
EmailServic
EmailServic IEmail
IEmail
Before After e
e Service
Service
CREDITS & REFERENCES
Robert C Martin Clean Coder https://sites.google.com/site/unclebobconsultingllc /
Pablos SOLID Software Development | LosTechies.com
Derick Bailey - McLane Advanced Technologies, LLC
PluralSight Training - SOLID Principles of Object Oriented Design
http://pluralsight.com/training/Courses/TableOfContents/principles-oo-design
Marcin Zajczkowski - http://solidsoft.wordpress.com/
Images Used Under License
http://www.lostechies.com/blogs/derickbailey/archive/2009/02/11/solid-development-principles-in-motivational-
pictures.aspx
SRP Article
http://www.objectmentor.com/resources/articles/srp.pdf
Solid for your Language
http://stefanroock.files.wordpress.com/2011/09/solidforyourlanguage.pdf
HELP : ABOUT
Adnan Masood works as a system architect / technical lead for Green dot Corporation where
he developsSOA based middle-tier architectures, distributed systems, and web-applications
using Microsofttechnologies. He is a Microsoft Certified Trainer holding several technical
certifications, including MCPD(Enterprise Developer), MCSD .NET, and SCJP-II. Adnan is
attributed and published in print media and onthe Web; he also teaches Windows
Communication Foundation (WCF) courses at the University ofCalifornia at San Diego and
regularly presents at local code camps and user groups. He is activelyinvolved in the .NET
community as cofounder and president of the of San Gabriel Valley .NET Developers group.
COHESION:
COUPLING:
E N C A P S U L AT I O N :
a reason to change
Email
Sending App
File
SRP: SINGLE RESPONSIBILITY
EXAMPLE APP NEW REQUIREMENTS: SEND FROM NON-WINFORMS APP. READ XML OR
FLAT FILE
Email
Sending App
Email
Sender
Email
Sender
Format
Reader
Related Fundamentals:
o Open/Closed Principle
o Interface Segregation Principle
o Separation of Concerns
Recommended Reading:
o Clean Code by Robert C. Martin [http://amzn.to/Clean-Code]
THE OPEN / CLOSED PRINCIPLE
OCP: THE OPEN/CLOSED PRINCIPLE
Wikipedia
THE OPEN / CLOSED
PRINCIPLE
Open to Extension
New behavior can be added in the future
Closed to Modification
Changes to source or binary code are not required
Remember TANSTAAFL
There Aint No Such Thing As A Free Lunch
OCP adds complexity to design
No design can be closed against all changes
SUMMARY
Related Fundamentals:
Recommended Reading:
IFileFormat
Reader
Database
Flat File XML File Connection
File
LSP: LISKOV SUBSTITUTION PRINCIPLE
E X AM PL E AP P: C O R R E C TI NG F OR L SP M OV E TH E DATAB AS E R E ADE R
Database
Databas Reader
e Service
Email
Flat File Sender
IFileFormat FileReader
Reader Service
XML File
INVARIANTS
o Dont interrogate objects for their internals move behavior to the object
o Tell the object what you want it to do
Recommended Reading:
oAgile Principles, Patterns, and Practices by Robert C. Martin and Micah
Martin [http://amzn.to/agilepppcsharp]
THE INTERFACE SEGREGATION
PRINCIPLE
ISP: THE INTERFACE
SEGREGATION PRINCIPLE
The Interface Segregation Principle
states that Clients should not be
forced to depend on methods they do
not use.
Agile Principles, Patterns, and Practices in C#
Corollary:
Prefer small, cohesive interfaces to fat interfaces
WHATS AN INTERFACE?
Interface keyword/type
public interface IDoSomething { }
Database
EmailSender EmailSender Reader
Service
SendEmail SendEmail
ReadFile GetMessageBod
ReadFromDb y
FileReader
Service
GetMessageBod
y
THE PROBLEM
Client Class (Login Control) Needs This:
THE PROBLEM
If you find fat interfaces are problematic but you do not own
them
o Create a smaller interface with just what you need
o Implement this interface using an Adapter that implements the full
interface
ISP TIPS
Related Fundamentals:
oPolymorphism
oInheritance
oLiskov Substitution Principle
oFaade Pattern
Recommended Reading:
oAgile Principles, Patterns, and Practices by Robert C. Martin and Micah Martin
[http://amzn.to/agilepppcsharp]
THE DEPENDENCY INVERSION
PRINCIPLE
DIP: DEPENDENCY INVERSION
PRINCIPLE
WHAT IS IT THAT MAKES A DESIGN RIGID, FRAGILE AND IMMOBILE?
IT IS THE INTERDEPENDENCE OF THE MODULES WITHIN THAT
DESIGN. A DESIGN IS RIGID IF IT CANNOT BE EASILY CHANGED.
SUCH RIGIDITY IS DUE TO THE FACT THAT A SINGLE CHANGE TO
HEAVILY INTERDEPENDENT SOFTWARE BEGINS A CASCADE OF
CHANGES IN DEPENDENT MODULES.
- ROBERT MARTIN
Dependency
Depender
DIP: THE DEPENDENCY
INVERSION PRINCIPLE
High-level modules should not depend on
low-level modules. Both should depend on
abstractions.
ThisClass
ThatClass
AnotherClass
DIP: DEPENDENCY
INVERSION PRINCIPLE
IDoSomethin
g
ThisClass
IWhatever
ThatClass
AnotherClass
DIP: DEPENDENCY
INVERSION PRINCIPLE
IDoSomethin
g
IWhatever ThisClass
ThatClass
IDoSomethin
AnotherClass
g
IWhatever
DIP: DEPENDENCY
INVERSION
PRINCIPLE
AnotherClass
IWhatever
IWhatever
ThatClass
IDoSomethin
g
IDoSomethin
g
ThisClass
DIP: DEPENDENCY
INVERSION
PRINCIPLE
EXAMPLE APP: CONSTRUCTOR DEPENDENCIES IN A PROCESSING SERVICE
Xml File Flat File
Reader Reader
IFileFormat
Reader
Database
File Reader Email
Reader
Service Sender
Service
IMessageInfoRetri
IEmailService
ever
ProcessingService
WHAT ARE DEPENDENCIES?
Framework
Third Party Libraries
Database
File System
Email
Web Services
System Resources (Clock)
Configuration
The new Keyword
Static methods
Thread.Sleep
Random
TRADITIONAL PROGRAMMING
AND DEPENDENCIES
High Level Modules Call Low Level Modules
Result
oTight coupling
oNo way to change implementation details (OCP violation)
oDifficult to test
DEPENDENCY INJECTION
Strategy Pattern
Pros
o Classes self-document what they need to perform their work
o Works well with or without a container
o Classes are always in a valid state once constructed
Cons
o Constructors can have many parameters/dependencies (design smell)
o Some features (e.g. Serialization) may require a default constructor
o Some methods in the class may not require things other methods require (design smell)
PROPERTY INJECTION
Pros
o Dependency can be changed at any time during object lifetime
o Very flexible
Cons
o Objects may be in an invalid state between construction and setting of
dependencies via setters
o Less intuitive
PARAMETER INJECTION
Cons
o Breaks method signature
o Can result in many parameters (design smell)
Or
DataAccess.SaveCustomer(myCustomer);
WHERE DO WE INSTANTIATE
OBJECTS?
Applying Dependency Injection typically results in many interfaces that eventually need to be
instantiated somewhere but where?
Default Constructor
o You can provide a default constructor that news up the instances you
expect to typically need in your application
o Referred to as poor mans dependency injection or poor mans IoC
Main
Dont force high-level modules to depend on low-level modules through direct instantiation or
static method calls
Related Fundamentals:
oSingle Responsibility Principle
oInterface Segregation Principle
oFaade Pattern
oInversion of Control Containers
Recommended Reading:
oAgile Principles, Patterns, and Practices by Robert C. Martin and Micah Martin
[http://amzn.to/agilepppcsharp]
ohttp://www.martinfowler.com/articles/injection.html
TRADITIONAL (NAVE) LAYERED
ARCHITECTURE
INVERTED ARCHITECTURE
THE PROBLEM
Result
o Tight coupling
o No way to change implementation details without recompile (OCP
violation)
o Difficult to test
DEPENDENCY INJECTION
Dependency is transitive
o If UI depends on BLL depends on DAL depends on Database Then
*everything* depends on the Database
Related Fundamentals:
o Open Closed Principle
o Interface Segregation Principle
o Strategy Pattern
Recommended Reading:
o Agile Principles, Patterns, and Practices by Robert C. Martin and Micah Martin
[http://amzn.to/agilepppcsharp]
o http://www.martinfowler.com/articles/injection.html
DONT REPEAT YOURSELF
Every piece of knowledge must have a single, unambiguous
representation in the system.
The Pragmatic Programmer
Variations include:
Once and Only Once
Duplication Is Evil (DIE)
ANALYSIS
Magic Strings/Values
Duplicate logic in multiple locations
Repeated if-then logic
Conditionals instead of polymorphism
Repeated Execution Patterns
Lots of duplicate, probably copy-pasted, code
Only manual tests
Static methods everywhere
MAGIC STRINGS / VALUES
DUPLICATE LOGIC IN MULTIPLE
LOCATIONS
REPEATED IF-THEN LOGIC
CONDITIONAL INSTEAD OF
POLYMORPHISM
Example of Flags Over Objects anti-
pattern
Violates the Tell, Dont Ask principle (aka
DIP)
SUMMARY
Recommended Reading:
o The Pragmatic Programmer: From Journeyman to Master
http://amzn.to/b2gJdK
o 97 Things Every Programmer Should Know http://amzn.to/cAse1Y
STATIC METHODS
Tightly coupled
Difficult to test
Related Fundamentals:
o Template Method Pattern
o Command Pattern
o Dependency Inversion Principle
Recommended Reading:
o The Pragmatic Programmer: From Journeyman to Master http://amzn.to/b2gJdK
o 97 Things Every Programmer Should Know http://amzn.to/cAse1Y
REPEATED EXECUTION
PATTERNS
DUPLICATE, COPY PASTED
CODE
Too Numerous to List
Commercial Tool (free version
available)
o Atomiq (http://GetAtomiq.com)
CONSIDER CODE GENERATION
T4 Templates
o Custom code generation templates
o Built into Visual Studio 2010
Commercial Tools:
o CodeSmith
o CodeBreeze
o CodeHayStack
REPETITION IN PROCESS
Testing
o Performing testing by hand is tedious and wasteful
Builds
o Performing builds by hand is tedious and wasteful
Deployments
o Performing deployments by hand is tedious and wasteful
Recommended Reading:
o The Pragmatic Programmer: From Journeyman to Master http://amzn.to/b2gJdK
o 97 Things Every Programmer Should Know http://amzn.to/cAse1Y
Related Tool
o Atomiq http://GetAtomiq.com
S.O.L.I.D. CONVERSION
EXAMPLE APP: BEFORE AND
A FT E R
SUMMARY
IMessageInfo
IMessageInfo IEmailSender
IEmailSender
Retriever
Retriever
Email
EmailProcessingService
Sending EmailProcessingService
App
Database
Database
Databas
Databas Reader
Flat Reader
Flat File
File e
e Service
Service
IMessage
IMessage
Info
Info
Retriever
Retriever
File IFileFormat
IFileFormat FileReader
FileReader
XML
XML File
File Reader Service
Reader Service
EmailServic
EmailServic IEmail
IEmail
Before After e
e Service
Service
LOW COUPLING: OCP, DIP,
PRINCIPLES
IMessageInfo
IMessageInfo IEmailSender
IEmailSender
Retriever
Retriever
EmailProcessingService
EmailProcessingService
Database
Database
Databa
Databa Reader
Flat
Flat File
File Reader
se
se Service
Service IMessage
IMessage
Info
Info
Retriever
Retriever
IFileFormat
IFileFormat FileReader
FileReader
XML
XML File
File Reader Service
Reader Service
EmailServic
EmailServic IEmail
IEmail
e
e Service
Service
S.O.L.I.D. -> OO HI G H C OHE SI ON : LOW
C OU PLI NG + SRP, LSP
PRINCIPLES
IMessageInfo
IMessageInfo IEmailSender
IEmailSender
Retriever
Retriever
EmailProcessingService
EmailProcessingService
Database
Database
Databas
Databas Reader
Flat Reader
Flat File
File e
e Service
Service
IMessage
IMessage
Info
Info
Retriever
Retriever
IFileFormat
IFileFormat FileReader
FileReader
XML
XML File
File Reader Service
Reader Service
IEmail
IEmail
EmailService
EmailService Service
Service
S.O.L.I.D. -> OO ENCAPSULATION:
SRP, LSP, DIP
PRINCIPLES
IMessageInfo
IMessageInfo IEmailSender
IEmailSender
Retriever
Retriever
EmailProcessingService
EmailProcessingService
Database
Database
Databa
Databa Reader
Flat
Flat File
File Reader
se
se Service
Service IMessage
IMessage
Info
Info
Retriever
Retriever
IFileFormat
IFileFormat FileReader
FileReader
XML
XML File
File Reader Service
Reader Service
EmailServic
EmailServic IEmail
IEmail
e
e Service
Service
QUESTIONS?
THANK YOU!
Adnan Masood
adnanmasood@acm.org
@adnanmasood
Blog: blog.AdnanMasood.com
Pasadena .NET User Group: www.sgvdotnet.org