8/22/2019 Solid Principal
1/66
Fundamentals:
TheSingleRes
ponsibilityPrinciple
SteveSm
ith
http
://pluralsight.co
m/
Outl
ine
SRP
Defined
The
Problem
An
Example
Ref
actoringtoApp
lySRP
RelatedFundamen
tals
8/22/2019 Solid Principal
2/66
SRP:TheSingleResp
onsibilityP
rinciple
TheS
ingleRespo
nsibilityPrinciplestatesthatevery
objectshouldhaveasingl
eresponsibility,andthat
res
ponsibilityshouldbeentirelyencapsulatedby
the
class.
Wikipe
dia
There
shouldnev
erbemorethanonereasonfora
cla
sstochange.
Rob
ertC.
Unc
leBobMartin
8/22/2019 Solid Principal
3/66
Cohesionan
dCoupling
Cohesion:howstro
ngly-relatedan
dfocusedarethevarious
responsibilitiesofamodule
Coupling:thedegr
eetowhicheachprogrammod
ulereliesoneach
oneoftheothermodules
Str
iveforl
owc
oup
ling
andhigh
cohesion!
Responsibilitiesar
eAxesofC
hange
Req
uirementschangestypicallym
aptoresponsib
ilities
Mo
reresponsibilities==Morelikelihoodofchange
Havingmultipleresponsibilitieswithinaclasscou
plestogetherth
ese
responsibilities
The
moreclassesac
hangeaffects,themorelikelyth
echangewill
intr
oduceerrors.
8/22/2019 Solid Principal
4/66
Dem
o
TheProblemWithTooMa
nyResponsibilities
7
ThePro
blem
Cas
hTransactionsDontNeedCreditCardProcess
ing
PointofSaleTransactionsDontNeedInventoryReservations
Storeinventoryis
updatedseparate
lyinoursystem
PointofSaleTransactionsDontNeedEmailNotifi
cations
Thecustomerdoesntprovideanemail
Thecustomerkno
wsimmediatelythattheorderwas
asuccess
Anychangetonotifications,credit
cardprocessing,orinventory
ma
nagementwilla
ffectOrderasw
ellastheWebandPointofSale
implementationso
fOrder!
8/22/2019 Solid Principal
5/66
Dem
o
Refactoring
toaBetterDesign
9
WhatisaRes
ponsibility
?
areasontochang
e
Ad
ifferenceinusagescenariosfro
mtheclientsperspective
Mu
ltiplesmallinte
rfaces(followIS
P)canhelptoachieveSRP
8/22/2019 Solid Principal
6/66
Summ
ary
FollowingSRPlead
stolowercoup
lingandhigher
cohesion
Ma
nysmallclasses
withdistinctre
sponsibilitiesre
sultinamore
flexibledesign
RelatedFundamen
tals:
Open/ClosedPrin
ciple
InterfaceSegrega
tionPrinciple
SeparationofCon
cerns
RecommendedReading:
CleanCodebyRo
bertC
.Martin[http://amzn.t
o/Clean
-Code]
Cred
its
ImagesUsedUnde
rLicense
http://www.l
ostechies.com/blogs/d
erickbailey/archiv
e/2009/02/11/solid-
development-principles-in-motivat
ional-pictures.aspx
SRPArticle
http://www.o
bjectmentor.com/resources/articles/srp
8/22/2019 Solid Principal
7/66
Formorein-depthonline
developertra
iningvisit
on-demandcontentfromauthorsyou
trust
Fundamentals:
TheOp
en/Close
dPrinciple
SteveSm
ith
http
://pluralsight.co
m/
8/22/2019 Solid Principal
8/66
Outline
OC
PDefined
TheProblem
An
Example
RefactoringtoApp
lyOCP
RelatedFundamen
tals
OCP:TheOpen/C
losedPrinciple
TheO
pen/Close
dPrinciplestatesthats
oftware
entities(classe
s,modules,functions,e
tc.)shouldbe
op
enforexten
sion,butclosedformodification.
Wikipe
dia
8/22/2019 Solid Principal
9/66
The
Open/Clo
sedPrincip
le
OpentoExtension
Ne
wbehaviorcanbeaddedinthefuture
ClosedtoModif
ication
Ch
angestoso
urceorbin
arycodear
enotrequired
Dr.BertrandMeyeror
iginatedtheOC
Pterminhis19
88book,
Object
OrientedSoftwareC
onstruction
8/22/2019 Solid Principal
10/66
Changebe
haviorwithoutchang
ingcode?
Relyonabstractions
Nolimittovariety
ofimplemen
tationsofeachabstraction
In.N
ET,abstractio
nsinclude:
Interfaces
Ab
stractBaseC
lasses
Inproceduralcode,somelevel
ofOCPcanbeachievedvia
pa
rameters
6
Dem
o
APriceCalculatorThatIsNo
tClosedToChan
ge
7
8/22/2019 Solid Principal
11/66
TheProblem
Ad
dingnewrulesrequirechanges
tothecalculatoreverytime
Eachchangecanin
troducebugsa
ndrequiresre-t
esting,e
tc.
We
wanttoavoidintroducingchangesthatcascad
ethroughman
y
mo
dulesinourapplication
Wr
itingnewclasse
sislesslikelyto
introduceprob
lems
Nothingdependsonnewclasses(y
et)
Newclasseshave
nolegacycouplin
gtomakethemh
ardtodesignortest
ThreeApproachestoAchieveOCP
Pa
rameters(Pro
ceduralProg
ramming)
Allowclienttocontrolbehavior
specificsviaap
arameter
Combinedwith
delegates/lamb
da,canbeverypowerfulapproa
ch
Inheritance/Te
mplateMeth
odPattern
Childtypesove
rridebehaviorofabaseclass(or
interface)
Co
mposition/S
trategyPatte
rn
Clientcodedep
endsonabstrac
tion
Providesapluginmodel
ImplementationsutilizeInheritance;Clientutiliz
esComposition
9
8/22/2019 Solid Principal
12/66
Dem
o
RefactoringtoaBetterDes
ign
10
W
hendowe
applyOCP?
ExperienceTellsYou
Ifyouknowfromyo
urownexperienceintheproblemd
omainthataparticular
classofchangeis
likelytorecur,yo
ucanapplyOCPu
pfrontinyourdesign
OtherwiseFoolme
once,shameon
you;foolmetw
ice,shameonme
Do
ntapplyOCPatfirst
Ifthemodulechan
gesonce,accep
tit.
Ifitchangesaseco
ndtime,refacto
rtoachieveOC
P
RememberTANSTAAF
L
The
reAintNoSuch
ThingAsAFree
Lunch
OC
Paddscomplex
itytodesign
No
designcanbec
losedagainstallchanges
8/22/2019 Solid Principal
13/66
Summ
ary
ConformancetoO
CPyieldsflexibility,reusability,andmaintainability
Knowwhichchang
estoguardaga
inst,andresistpremature
abstraction
RelatedFundamen
tals:
SingleResponsib
ilityPrinciple
StrategyPattern
TemplateMethodPattern
RecommendedReading:
AgilePrinciples,Patterns,andPracticesbyRobertC.MartinandMicah
Martin[http://am
zn.to/agilepppcsh
arp]
Credits
ImagesUsedUnde
rLicense
http://www.loste
chies.com/blogs/derickbailey/archive/2009/02/11/sol
id-
development-principles-in-motivational-pictures.asp
x
8/22/2019 Solid Principal
14/66
Formorein
-depthonline
developertrainingvisit
on-de
mandcontentfroma
uthorsyou
trust
Fun
damentals:
TheLiskovS
ubstitutio
nPrincip
le
SteveSm
ith
http://pluralsight.co
m/
8/22/2019 Solid Principal
15/66
Outline
LSPDefined
TheProblem
An
Example
RefactoringtoApp
lyLSP
RelatedFundamen
tals
LSP:The
LiskovSub
stitutionP
rinciple
TheLiskovSubstitutionPrin
ciplestates
thatSubtyp
es
mustbesubst
itutablefor
theirbasetypes.
AgilePr
inciples,Pa
tterns,and
Practicesin
C#
Nam
edforBarb
araLiskov,
whofirstdescribedthe
pr
inciplein1988.
8/22/2019 Solid Principal
16/66
Substitu
tability
Childclassesmustnot:
1)R
emovebas
eclassbehavior
2)V
iolatebase
classinvariants
And
ingeneralmustnotre
quirecallin
gcodeto
k
nowtheya
redifferent
fromt
heir
basetype.
8/22/2019 Solid Principal
17/66
InheritanceandtheIS-A
Relat
ionship
NaveOOPteache
suseofIS-Atodescribech
ildclasses
relationshiptobaseclasses
LSPs
uggeststhat
IS-Ashouldb
ereplacedw
ith
IS-SUBSTITUTABLE-FOR
6
Invariants
Co
nsistofreasona
bleassumption
sofbehaviorby
clients
Canbeexpressedasprecondition
sandpostconditionsformetho
ds
Fre
quently,unitte
stsareusedtospecifyexpectedbehaviorofa
me
thodorclass
De
signByContract
isatechniquet
hatmakesdefin
ingthesepre-and
po
st-conditionsex
plicitwithincodeitself.
To
followLSP,
derivedclassesmustnotviolatean
yconstraints
defined(orassumedbyclients)on
thebaseclasse
s
7
8/22/2019 Solid Principal
18/66
Dem
o
Violatin
gLSPusingShapes
8
TheProblem
No
n-substitutable
codebreakspo
lymorphism
Clientcodeexpectschildclassestoworkinplaceoftheirbasecla
sses
Fixingsubstituta
bilityproblems
byaddingif-thenorswitch
sta
tementsquicklybecomesama
intenancenightmare(andviola
tes
OC
P)
8/22/2019 Solid Principal
19/66
L
SPViolatio
nSmells
forea
ch
(var
emp
in
Employees
)
{if(
emp
is
Manag
er
)
{
_pr
in
ter.
Pr
in
tManager
(e
mpas
Manage
r);
}
els
e
{
_printer.Prin
tEmployee(em
p);
}
}
10
L
SPViolatio
nSmells
public
abstract
class
Base
{
p
ublic
abstract
void
Method1();
p
ublicabstract
void
Method2();
}
public
class
Child
:
Base
{
pu
blic
overr
idevo
id
Me
tho
d1()
{
throw
new
NotImplementedException()
;
}pu
blic
overridevoid
Method2()
{
//
dostuff
}
}
11
FollowI
SP!
Usesmallinterfacessoyou
don
trequireclassesto
implementmorethanthey
need!
8/22/2019 Solid Principal
20/66
Dem
o
RefactoringtoaBetterDes
ign
12
Whendow
efixLSP?
Ify
ounoticeobvio
ussmellsliketh
oseshown
Ify
oufindyourselfbeingbittenbytheOCPviolat
ionsLSPinvaria
bly
causes
8/22/2019 Solid Principal
21/66
LSPTips
Tell,
DontAsk
Dontinterrogateobjectsfortheirinternalsmoveb
ehaviortotheobject
Telltheobjectw
hatyouwantitto
do
Co
nsiderRefactoringtoanewBaseClass
Giventwoclasse
sthatsharealoto
fbehaviorbutare
notsubstitutable
Createathirdcla
ssthatbothcand
erivefrom
Ensuresubstitutabilityisretainedb
etweeneachclassandthenewbase
Summary
Co
nformancetoLSPallowsforproperuseofpoly
morphisma
nd
producesmoremaintainablecode
Re
memberIS-SUB
STITUTABLE-FO
RinsteadofIS-A
Re
latedFundamentals:
Polymorphism
Inheritance
InterfaceSegregationPrinciple
Open/ClosedPrinciple
Re
commendedRe
ading:
AgilePrinciples,Patterns,andPracticesbyRobertC.MartinandMicah
Martin[http://am
zn.to/agilepppcsharp]
8/22/2019 Solid Principal
22/66
Credits
Im
agesUsedUnderLicense
http://www.loste
chies.com/blogs/derickbailey/archive/2009/02/11/solid-
development-principles-in-motivational-pictures.asp
x
Formorein
-depthonline
developertrainingvisit
on-de
mandcontentfromauthorsyou
trust
8/22/2019 Solid Principal
23/66
Fun
damentals:
TheInterfaceS
egregationPrincip
le
SteveSm
ith
http://pluralsight.com/
Outline
ISPDefined
Th
eProblem
An
Example
Re
factoringtoApplyISP
Re
latedFundamentals
8/22/2019 Solid Principal
24/66
ISP:TheI
nterfaceSe
gregation
Principle
TheInterfaceSe
gregationP
rinciplestatesthatClients
sh
ouldnotbe
forcedtodependonmethodsthey
do
no
tuse.AgilePrinciples,Pa
tterns,and
PracticesinC#
Coro
llary:
P
refersmall,c
ohesiveinterfacestofat
interfaces
8/22/2019 Solid Principal
25/66
Whatsan
Interface?
Interfacekeyword/type
p
ublic
in
ter
face
I
Do
Some
thi
ng
{
}
Publicinterface
ofaclass
pu
blic
cla
ss
Some
Cl
ass
{
}
Wha
tdoestheclientseeanduse?
Dem
o
Violating
ISP
6
8/22/2019 Solid Principal
26/66
ThePr
oblem
ClientClass(LoginCo
ntrol)NeedsTh
is:
Forced
to
use
this
ThePr
oblem
Ab
outPagesimplyneedsApplicationNameandA
uthorName
Fo
rcedtodealwit
hhugeConfigu
rationSettingsc
lass
Fo
rcedtodealwit
hactualconfigu
rationfiles
InterfaceSegre
gationviolationsresultinclasses
th
atdepend
onthingstheydonotneed,
in
creasingco
uplingand
reducingflexibilityan
d
m
aintainability
8
8/22/2019 Solid Principal
27/66
Dem
o
Refactorin
gtoaBetterDesign
9
ISPSmells
Un
implementedinterfacemethods:
pu
blic
overr
ide
str
ing
Reset
Passwor
d(
st
ring
usernam
e,
str
ing
an
swer
)
{
throw
new
No
tImp
lement
edExcep
tion(
);
}
Rememberthese
violateLiskovSubstitution
Principle!
8/22/2019 Solid Principal
28/66
ISPSmells
Clientreferencesaclassbutonlyusessmallportionofit
WhendowefixISP?
Oncethereispain
Ifthereisnopain,theresnoproblemt
oaddress.
Ifyoufindyourselfdependingon
afatinterfaceyouown
Createasmaller
interfacewithjustwhatyouneed
Havethefatinte
rfaceimplementy
ournewinterface
Referencethenewinterfacewithy
ourcode
Ifyoufindfatinterfacesareproblematicbutyo
udonotownth
em
Createasmaller
interfacewithjustwhatyouneed
Implementthisinterfaceusingan
Adapterthatimplementsthefullint
erface
8/22/2019 Solid Principal
29/66
ISPTips
Ke
epinterfacessm
all,cohesive,a
ndfocused
Wheneverpossible,lettheclientdefinetheinterface
Wheneverpossible,packagetheinterfacewithth
eclient
Alternately,pack
ageinathirdasse
mblyclientandim
plementationbo
th
dependupon
Lastresort:Pa
ckageinterfaceswit
htheirimplementat
ion
Summary
Do
ntforceclientc
odetodependo
nthingsitdoesn
tneed
Ke
epinterfaceslea
nandfocused
Re
factorlargeinterfacessotheyinheritsmallerinte
rfaces
Re
latedFundamen
tals:
Polymorphism
Inheritance
LiskovSubstitutio
nPrinciple
FaadePattern
Re
commendedReading:
AgilePrinciples,P
atterns,andPracticesbyRobertC.
Ma
rtinandMicahMar
tin
[http://amzn.to/a
gilepppcsharp]
8/22/2019 Solid Principal
30/66
Credits
Im
agesUsedUnderLicense
http://www.lostechies.com/blogs/
derickbailey/archive/2009/02/11/so
lid-
development-principles-in-motiva
tional-pictures.aspx
Formorein
-depthonlinedevelopertr
ainingvisit
on-demandcontentf
roma
uthorsyou
trust
8/22/2019 Solid Principal
31/66
Fun
damentals:
TheD
ependencyInversionPrincip
le
Part1
SteveSm
ith
htt
p://pluralsight.com/
Out
line
DI
PDefined
Th
eProblem
An
Example
Re
factoringtoApplyDIP
Re
latedFundame
ntals
8/22/2019 Solid Principal
32/66
DIP:TheD
ependenc
yInversion
Principle
High
-levelmodulesshouldnotdepend
onlow-leve
l
m
odules.Bot
hshouldde
pendonabstractions.
Abstractionsshouldnotdependondetails.Details
sh
oulddepen
donabstractions.
AgilePrinciples,Pa
tterns,and
PracticesinC#
8/22/2019 Solid Principal
33/66
W
hataredependencies?
Framework
Th
irdPartyLibraries
Database
FileSystem
Em
ail
WebServices
Sy
stemResources
(Clock)
Co
nfiguration
Th
enew
Keyword
Staticmethods
Th
read.S
leep
Ra
ndom
5
T
raditional
Programm
ingandDe
pendencies
HighLevelModul
esCallLowLevelModules
UserInterfacedep
endson
BusinessLogicd
ependson
Infrastructure
Utility
DataAccess
StaticmethodsareusedforconvenienceorasFa
adelayers
Classinstantiation/Callstacklog
icisscatteredth
roughallmodu
les
ViolationofSing
leResponsibilityP
rinciple
6
8/22/2019 Solid Principal
34/66
Class
Dependen
cies:BeHo
nest!
Classconstructorsshouldrequire
anydependenciestheclassneeds
Classeswhoseconstructorsmake
thisclearhave
explicitdependencies
Classesthatdono
thaveimplicit,hiddendependencies
7
publicclassHelloW
orldHidden
{
publicstringHello(stringname)
{
if(DateTime.N
ow.Hour