SlideShare une entreprise Scribd logo
1  sur  128
Télécharger pour lire hors ligne
The	
  Open	
  Closed	
  Principle
Part	
  I
The	
  Original	
  Version
©	
  2014	
  Philip	
  Schwarz
https://twitter.com/philip_schwarz
philip.johann.schwarz@gmail.com
This	
  work	
  is	
  licensed	
  under	
  a	
  Creative	
  Commons	
  Attribution-­‐NonCommercial-­‐NoDerivs 3.0	
  Unported
License.
Tension	
  Between
known	
  
needs	
  
of	
  today
changes	
  that	
  
will	
  arrive	
  in	
  
the	
  future
Sandi	
  Metz
The	
  Fundamental	
  Target	
  of	
  
Design
Code	
  needs	
  to	
  
work	
  today	
  just	
  
once,
and	
  it	
  needs	
  to	
  be	
  easy	
  to	
  change	
  forever
It	
  is	
  at	
  this	
  point	
  of	
  tension
where	
  design	
  matters
today’s
needs	
  
future
changes
its	
  purpose,	
  its	
  entire	
  reason	
  
for	
  being,	
  is	
  to	
  reduce	
  the	
  
cost	
  of	
  change.
1999
3rd Apr	
  2014	
  
@KentBeck design is	
  irrelevant	
  for	
  today.	
  it	
  only	
  matters	
  when	
  we	
  want	
  to	
  change	
  the	
  
software...
@KentBeck change	
  is	
  the	
  only	
  reason	
  to	
  organize	
  software	
  at	
  all…
Kent	
  Beck
adopted	
  by	
  agile	
  
community	
  as	
  a	
  truth	
  
about	
  software	
  
development
Henrik
Christensen 2010
“software	
  must	
  be	
  designed	
  and	
  developed	
  to	
  
make	
  it	
  easy	
  to	
  change”
Let’s	
  examine	
  software	
  qualities	
  that	
  enable
ease	
  of	
  change	
  
Look	
  for	
  definitions	
  in	
  ISO	
  9126
Projects	
  sometimes	
  fail due	
  to	
  not	
  having	
  any	
  clear	
  
definitions	
  of	
  "success”
This	
  standard	
  tries	
  to	
  develop	
  a	
  common	
  understanding	
  of	
  
project	
  objectives	
  and	
  goals,	
  e.g.	
  software	
  qualities
Software	
  is	
  Reliabile if	
  it	
  can	
  maintain	
  a	
  
specific	
  level	
  of	
  performance under	
  specific	
  
usage	
  conditions
in	
  our	
  
setting…
In	
  particular,	
  we	
  are	
  interested	
  in
preserving	
  reliability	
  in	
  the	
  face	
  of	
  change	
  
Software	
  is	
  Reliabile if	
  it	
  can	
  perform	
  the	
  
required	
  functions	
  without	
  failing	
  
“maintainability is	
  composed	
  of	
  
several,	
  finer	
  grained,	
  qualities”
Analysability
Maintainability
Changeability Stability Testability
Software	
  is	
  Analysable if	
  you	
  can
• diagnose	
  it	
  for	
  
§ deficiencies
§ causes	
  of	
  failure
• identify	
  the	
  parts	
  to	
  be	
  modified
“Analysability is	
  basically	
  the	
  ability	
  to	
  understand
software”
Analysability
Maintainability
Changeability Stability Testability
Software	
  is	
  changeable	
  if	
  it	
  allows	
  you	
  to
• implement	
  a	
  specific	
  modification
• add,	
  modify,	
  or	
  enhance	
  a	
  feature	
  
at	
  a	
  reasonable	
  cost
“almost	
  all	
  Design	
  Patterns are	
  
geared	
  towards	
  increasing	
  
design’s	
  changeability”
Analysability
Maintainability
Changeability Stability Testability
“Software	
  is	
  flexible	
  if	
  you	
  can	
  add/enhance	
  	
  
functionality	
  purely	
  by	
  adding	
  software units	
  
and	
  specifically	
  not	
  by	
  modifying	
  existing	
  
software	
  units”
Flexibility a	
  special	
  case	
  of	
  
changeability
Changeability
Behavioural changes	
  that	
  are	
  introduced	
  
by	
  modifying existing	
  production	
  code
Changeability	
  is	
  a	
  desirable	
  quality,	
  
but it	
  relies	
  on
Change	
  by	
  Modification
Change	
  by	
  
Modification
“The	
  less	
  I	
  ever	
  modify	
  a	
  class,	
  the	
  higher	
  the	
  probability	
  that	
  
it	
  will	
  remain	
  free	
  of	
  defects”
Modifications	
  carry	
  the	
  risk	
  of	
  introducing	
  defects,	
  and	
  the	
  
necessary	
  cost	
  of	
  avoiding	
  them:	
  testing,	
  code	
  reviewing,	
  etc.
Behavioural changes	
  that	
  are	
  introduced	
  
by	
  modifying existing	
  production	
  code
Change	
  by	
  
Modification
Change	
  by	
  
Addition
Behavioural changes	
  that	
  are	
  introduced	
  by	
  
adding new	
  production	
  code	
  instead	
  of	
  
modifying	
  existing	
  code
Contrast	
  
Change	
  by	
  Addition	
  avoids	
  (risky)	
  modifications	
  altogether
with
Changeability
Change	
  by	
  
Addition
Change	
  by	
  
Modification
Changeability	
  does	
  not	
  take	
  a	
  stand	
  point	
  with	
  regards	
  
to	
  the	
  way	
  a	
  specified	
  modification	
  is	
  implemented
Flexibility
In	
  contrast,	
  Flexibility	
  does	
  take	
  this	
  stand	
  point	
  
and	
  requires	
  that	
  no	
  modifications	
  are	
  made
Analysability
Maintainability
Changeability Stability Testability
Software	
  is	
  Stable	
  if	
  it	
  avoids	
  unexpected	
  effects	
  when	
  
modified
“I	
  advocate	
  the	
  practice	
  to	
  avoid	
  modifying	
  existing	
  code	
  but	
  
preferably	
  add	
  features	
  or	
  modify	
  existing	
  ones by	
  other	
  
means”
Flexibility
“any	
  change	
  to	
  existing	
  software	
  carries	
  a	
  risk	
  of	
  introducing	
  
defects”
Changeability
Stability
Flexibility
Reliability
Change	
  by	
  
Modification
Change	
  by	
  
Addition
-­‐
+ -­‐
+
Summary
+ supports
-­‐ risks	
  undermining
relies	
  on
Question:	
  how	
  do	
  we	
  promote	
  flexibility,	
  
reliability	
  and	
  stability	
  in	
  our	
  software?
Analysability
Maintainability
Changeability Stability Testability
Flexibility
Reliability
Answer:	
  we	
  favour ‘Change	
  by	
  Addition’	
  over	
  	
  
‘Change	
  by	
  Modification’
Changeability
Stability
Flexibility
Reliability
Change	
  by	
  
Modification
Change	
  by	
  
Addition
-­‐
+ -­‐
+
I	
  cover	
  techniques	
  that	
  
focus	
  on	
  flexibility	
  
Christensen
if	
  you	
  require	
  
that	
  s/w	
  can	
  
adapt	
  to	
  
changing	
  
requirements
without	
  
modifying	
  
the	
  
production	
  
code
then	
  you	
  need	
  to	
  
employ	
  a	
  SPECIAL	
  
set	
  of	
  design	
  and	
  
programming	
  
techniques	
  as	
  well	
  
as	
  adopt	
  a	
  
SPECIAL	
  mindset
“Another	
  way	
  of	
  characterising
Change	
  by	
  Addition	
  that	
  you	
  may	
  
come	
  across	
  is	
  the	
  Open	
  Closed	
  
Principle”
How	
  do	
  we	
  achieve	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  ?Change	
  by	
  
Addition
The	
  Open-­‐Closed	
  Principle
Modules	
  should	
  be	
  both	
  open	
  and	
  closed
Bertrand	
  Meyer
Object	
  Oriented	
  
Software	
  Construction
The	
  most	
  comprehensive,	
   definitive	
  
OO	
  reference	
  ever	
  published1988
Isn’t	
  there	
  a	
  contradiction
between	
  the	
  two	
  terms?
Modules	
  should	
  be	
  both	
  
OPEN	
  and	
  CLOSED
¬(p	
  ∧ ¬p)	
  
The contradiction	
  is	
  only	
  apparent
The	
  two	
  terms	
  
correspond	
  to	
  
goals	
  of	
  a	
  
different	
  nature
e.g.	
  a	
  Dutch	
  door	
  can	
  be	
  
both OPEN	
  and CLOSED
It	
  is	
  a	
  
So	
  let’s	
  look	
  at	
  the	
  goals	
  of	
  the	
  OCP
OCP
A	
  module	
  is	
  
said	
  to	
  be	
  
OPEN
if	
  it	
  is	
  still	
  
available	
  for	
  
extension
or	
  add fields to	
  its	
  data	
  
structures Data	
  Structures
fields
+
operations
e.g.	
  it	
  should	
  be	
  possible	
  to	
  
expand its	
  set	
  of	
  operations	
  
A	
  module	
  is	
  
said	
  to	
  be	
  
CLOSED
If	
  it	
  is	
  available	
  
for	
  use by	
  
other	
  modules
Has	
  a	
  well-­‐defined,	
  stable description	
  
(its	
  interface – in	
  information	
  hiding	
   sense)
public	
  part
secret	
  part
interface
1
can	
  be	
  compiled,	
   stored	
  in	
  a	
  library,	
  and	
  made	
  
available	
  for	
  clients	
  to	
  use2
in	
  the	
  case	
  of	
  a	
  design	
  or	
  specification	
  module:
• approved
• baselined in	
  version	
  control
• its	
  interface	
  published	
  	
  for	
  benefit	
  of	
  other	
  module	
  authors
3
OPEN
if	
  it	
  is	
  still	
  
available	
  for	
  
extension
CLOSED
If	
  it	
  is	
  available	
  
for	
  use by	
  
other	
  modules
Recap	
  – A	
  module	
  is…
It	
  is	
  impossible	
  to	
  foresee	
  all	
  the	
  elements	
  
that	
  a	
  module	
  will	
  need	
  in	
  its	
  lifetime X
The	
  need	
  for	
  	
   ness
so	
  developers	
  wish	
  to	
  keep	
  the	
  module	
  open	
  for	
  as	
  long	
  as	
  possible
so	
  that	
  they	
  can	
  address	
  changes,	
  
and	
  extensions	
  
by	
  changing	
  elements	
  or	
  
adding	
  new	
  elements
The	
  need	
  for	
  	
   ness
if	
  a	
  module	
  is	
  never	
  closed	
  until	
  it	
  is	
  certain	
  
that	
  it	
  contains	
  all	
  the	
  needed	
  features	
  
x
every	
  developer	
  would	
  always	
  be	
  waiting	
  for	
  
completion	
  of	
  another	
  developer's	
  job
then	
  multi-­‐module	
   s/w	
  can	
  
never	
  reach	
  completionx
in	
  a	
  system	
  consisting	
  of	
  many	
  modules,	
   most	
  
modules	
  will	
  depend	
  on	
  some	
  others
but	
  it	
  is	
  also	
  necessary	
  to	
  close	
  modules
Modules	
  should	
  be	
  both	
  open	
  and	
  closed
We	
  want	
  modules	
  to	
  be	
  both	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  for	
  extension	
  and	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  for	
  modification
the	
  two	
  goals	
  of	
  
openness	
  and	
  closedness
with	
  traditional	
  
techniques
are	
  incompatible
either	
  you	
  keep	
  a	
  module	
  open	
  
and	
  others	
  cannot	
  use	
  it	
  yet
and	
  any	
  change	
  or	
  
extension	
  can	
  trigger	
  a	
  
painful	
  chain	
  reaction	
  of	
  
changes
or	
  you	
  close	
  it	
  
in	
  many	
  other	
  modules	
  
which	
  relied	
  on	
  the	
  
original	
  module	
  directly	
  
or	
  indirectly
AB C
D
E
A	
  module	
  and	
  its	
  clients
A’F
G H I
New	
  clients	
  which	
  need	
  A’,	
  an	
  adapted	
  or	
  extended	
  version	
  of	
  A
Typical	
  situation	
  where	
  the	
  needs	
  for	
  Open	
  and	
  Closed	
  
modules	
  are	
  hard	
  to	
  reconcile
=	
  	
  client	
  of
With	
  non-­‐OO	
  methods,	
  
there	
  seem	
  to	
  be	
  only	
  2	
  solutions,	
  
equally	
  unsatisfactory
AB C
D
E
AF
G H I
Solution	
  1
AB C
D
E
AF
G H I
Solution	
  1
AB C
D
E
A’F
G H I
Solution
We	
  have	
  taken	
  a	
  copy	
  of	
  A	
  and	
  modified	
   it,	
  turning	
   it	
  into	
  the	
  desired	
  A’
Solution
Meyer’s	
  Assessment
the	
  consequences	
  are	
  appalling
an	
  explosion	
  of	
  variants
of	
  the	
  original	
  module,	
  
many	
  of	
  them	
  very	
  similar,
but	
  never	
  quite	
  identical
if	
  you	
  extrapolate	
  its	
  effects	
  to	
  
• many modules	
  
• many modification	
  requests	
  
• a	
  long period	
  of	
  time
Solution	
  (Source	
  tree	
  copy)
Christensen’s	
  Assessment
Probably	
  the	
  main	
  reason	
  it	
  is	
  encountered	
  so	
  often	
  in	
  practice
Easy	
  to	
  explain	
  to	
  colleagues	
  &	
  new	
  developers	
  
No	
  implementation	
  interferenceX
Solution	
  (Source	
  tree	
  copy)
Christensen’s	
  Assessment
Quick	
  but	
  very	
  dangerous
In	
  the	
  long	
  run	
  it	
  is	
  
often	
  a	
  real	
  disaster…
The	
  solution	
  has	
  severe	
  
limitations.	
  
because	
  it	
  leads	
  to	
  the
multiple	
  maintenance	
  problem
Solution	
  (Source	
  tree	
  copy)
Christensen’s	
  Assessment
when	
  you	
  want	
  to	
  add/modify	
  logic	
  
you	
  have	
  to:
• Do	
  it	
  for	
  each	
  source	
  tree
• Write	
  the	
  same	
  test	
  cases	
  for	
  each	
  
source	
  tree
you	
  have	
  to	
  do	
  it	
  in	
  
each	
  source	
  tree
when	
  you	
  need	
  to	
  
remove	
  a	
  defect	
  
DRIFT
Practice	
  shows	
  that	
  over	
  time	
  the	
  
source	
  trees	
  evolve	
  into	
  completely	
  
different	
  directions:	
  they	
  drift	
  apart.
After	
  a	
  while	
  it	
  is	
  more	
  or	
  
less	
  like	
  maintaining a	
  set	
  
of	
  completely	
  different	
  
applications
At	
  that	
  point,	
  before	
  you	
  do	
  any	
  of	
  
the	
  operations,	
  you	
  have	
  to	
  first	
  
analyse each source	
  tree!!
Used	
  in	
  airports	
  to	
  generate	
  reports	
  of	
  local	
  weather
one	
  variant	
  for	
  each	
  airport	
  in	
  Denmark
init and	
  config code
Example
SAWOS -­‐ Semi	
  Automatic	
  Weather	
  Observation	
  System
8	
  copies!!!
Analysability Stability Reliability
solution
-­‐ -­‐ -­‐
Summary
multiple	
  maintenance	
  problem
That	
  was	
  Meyer’s	
  first	
  unsatisfactory
solution
to	
  the	
  problem	
  of	
  making	
  modules	
  
both	
  OPEN	
  and	
  CLOSED
Let’s	
  turn	
  to	
  the	
  second	
  one
AB C
D
E
A’F
G H I
A	
  module	
  and	
  its	
  clients
New	
  clients	
  which	
  need	
  A’,	
  an	
  adapted	
  or	
  extended	
  version	
  of	
  A
=	
  	
  client	
  of
Problem
Solution	
  2
AB C
D
E
A’F
G H I
Change	
  by	
  
Modification
A+B C
D
E
A’F
G H I
We	
  have	
  modified	
   A	
  into	
  A+,	
  which	
  can	
  switch	
  between	
  two	
  modes	
  of	
  execution
In	
  one	
  mode	
  it	
  behaves	
  like	
  A,	
  and	
  in	
  the	
  other	
  it	
  behaves	
  as	
  expected	
  of	
  A’	
  
Solution
A+B C
D
E
A’F
G H I
We	
  have	
  modified	
   A	
  into	
  A+,	
  which	
  can	
  switch	
  between	
  two	
  modes	
  of	
  execution
In	
  one	
  mode	
  it	
  behaves	
  like	
  A,	
  and	
  in	
  the	
  other	
  it	
  behaves	
  as	
  expected	
  of	
  A’	
  
Solution
A+B C
D
E
A’F
G H I
if	
  (variant	
  ==	
  VARIANT_1)
then	
  {
….	
  
}	
  else	
  {
….
}	
  
At	
  points	
  of	
  variation,	
  A+	
  looks	
  like	
  this:
We	
  have	
  modified	
   A	
  into	
  A+,	
  which	
  can	
  switch	
  between	
  two	
  modes	
  of	
  execution
In	
  one	
  mode	
  it	
  behaves	
  like	
  A,	
  and	
  in	
  the	
  other	
  it	
  behaves	
  as	
  expected	
  of	
  A’	
  
Alternatively,	
  this	
  can	
  
be	
  a	
  switch
Solution
A+B C
D
E
A’F
G H I
Solution	
  – Meyer’s	
  Assessment
A+B C
D
E
A’F
G H I
The	
  potential	
  for	
  disaster is	
  obvious:	
   changes	
  to	
  A	
  may	
  invalidate	
  the	
  assumptions	
  on	
  the	
  
basis	
  of	
  which	
  the	
  old	
  clients	
  used	
  A.
So	
  the	
  changes	
  may	
  start	
  a	
  dramatic	
  series	
  of	
  changes	
  in	
  clients,	
  client	
  of	
  clients....etc
Solution	
  – Meyer’s	
  Assessment
A+
A’F
G H I
Solution	
  – Meyer’s	
  Assessment
The	
  potential	
  for	
  disaster	
  is	
  obvious:	
   changes	
  to	
  A	
  may	
  invalidate	
  the	
  assumptions	
  on	
  the	
  
basis	
  of	
  which	
  the	
  old	
  clients	
  used	
  A.
So	
  the	
  changes	
  may	
  start	
  a	
  dramatic	
  series	
  of	
  changes	
  in	
  clients,	
  client	
  of	
  clients....etc
B C E
D
this	
  is	
  a	
  nightmare	
  for	
  the	
  proj.	
  mgr.
the	
  system	
  regresses
and	
  several	
  modules	
   have	
  to	
  be	
  re-­‐
opened	
  for	
  
dev/test/debug/documentation
Even	
  though	
   the	
  Change	
  solution	
  has	
  this	
  problematic	
  ripple	
  effect,	
  it	
  is	
  still	
  better	
  than	
  
the	
  Copy	
  solution.
On	
  the	
  surface,	
  the	
  copy	
  solution	
  seems	
  better	
  because	
  it	
  avoids	
  the	
  ripple	
  effect	
  of	
  change
but	
  in	
  fact	
  it	
  may	
  even	
  be	
  more	
  catastrophic…it	
  only	
  postpones	
   the	
  day	
  of	
  reckoning
We	
  saw	
  earlier	
  the	
  risks	
  of	
  an	
  explosion	
  of	
  variants,	
  many	
  of	
  them	
  very	
  similar,	
  
but	
  never	
  quite	
  identical:
Solution	
  – Meyer’s	
  Assessment
solutionsolution
Solution	
  (Parametric	
  solution)
Christensen’s	
  Assessment
Conditionals	
  are	
  easy	
  to	
  understand.	
  So	
  approach	
  is	
  easy	
  to	
  
describe	
  to	
  other	
  developers.
Avoids	
  Multiple	
  Maintenance	
  Problem	
  
Only	
  one	
  code	
  base	
  to	
  maintain
solutionsolution
Liabilities,	
  most	
  of	
  which	
  deal	
  with	
  long	
  term	
  maintainability
Change	
  by	
  
Modification
Reliability	
  Concerns	
  – solution	
  relies	
  on	
  	
  
with	
  risk	
  of	
  
introducing	
  
new	
  defects
Analysability concerns	
  – as	
  more	
  and	
  more	
  
requirements	
  are	
  handled	
  by	
  parameter	
  
switching,	
  the	
  code	
  becomes	
  less	
  easy	
  to	
  
analyse
…
Responsibility	
  erosion	
  – the	
  software	
  has,	
  
without	
  much	
  notice,	
  been	
  given	
  an	
  extra	
  
responsibility
drives	
  
towards
Procedural
Design
Blob	
  aka
God	
  Class
Solution	
  (Parametric	
  solution)
Christensen’s	
  Assessment
A	
  reasonable	
  approach	
  at	
  first,	
  but	
  one	
  with	
  serious	
  problems
for	
  applications	
  that	
  need	
  to	
  grow	
  over	
  time
Solution	
  (Switches)
Shalloway’s Assessment
Not	
  too	
  bad	
  as	
  long	
  as	
  you	
  just	
  keep	
  adding	
  cases… 2004
but	
  soon	
  you	
  need	
  to	
  introduce	
  fall-­‐throughs…
…and	
  then	
  the	
  switches	
  are	
  not	
  as	
  nice	
  as	
  they	
  used	
  to	
  be
Eventually	
  you	
  need	
  to	
  start	
  adding	
  variations	
  within	
  a	
  case.	
  
I	
  like	
  to	
  call	
  this	
   switch
The	
  flow	
  of	
  the	
  switches	
  themselves	
  becomes	
  confusing,	
  hard	
  to	
  read,	
  hard	
  to	
  
decipher.
When	
  a	
  new	
  case	
  comes	
  in	
  the	
  programmer	
  must	
  find	
  every	
  place	
  it	
  can	
  
be	
  involved	
  (often	
  finding	
  all	
  but	
  one	
  of	
  them).
Suddenly	
   things	
  get	
  bad	
  in	
  a	
  hurry.	
  
Analysability Stability Reliability
solution
-­‐ -­‐ -­‐
Summary
Analysability Stability Reliability
solution
-­‐ -­‐ -­‐
With	
  non-­‐OO	
  methods,	
  there	
  are	
  only	
  only	
  2	
  solutions	
  available	
  to	
  us,	
  
BOTH	
  UNSATISFACTORY
multiple	
  maintenance	
  problem
Change	
  by	
  
Modification
CHANGE
COPY
If	
  non-­‐OO	
  methods	
  are	
  all	
  we	
  have,	
  then	
  
Meyer	
  says	
  we	
  face	
  a	
  change	
  or	
  copy	
  
dilemma
CHANGE COPY
AB C
D
E
A’F
G H I
So	
  how	
  can	
  we	
  have	
  modules	
  that	
  are	
  both	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  and	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  ?
How	
  can	
  we	
  keep	
  A	
  and	
  everything	
  in	
  the	
  top	
  part	
  of	
  the	
  figure	
  unchanged,	
  …
…while	
  providing	
   A’	
  to	
  the	
  bottom	
  clients,	
  and	
  avoiding	
  duplication	
  of	
  software?	
  
AB C
D
E
A’F
G H I
With	
  the	
  OO	
  concept	
  of	
  inheritance
Inheritance	
  allows	
  us	
  to	
  get	
  out	
  of	
  the	
  CHANGE	
  OR	
  COPY	
  dilemma…
…because	
  inheritance	
  allows	
  us	
  to	
  define	
  a	
  new	
  module	
  A'	
  in	
  terms	
  of	
  an	
  existing	
  
module	
  A,	
  …by	
  stating	
  only	
  the	
  differences	
  between	
  the	
  two	
  
A’	
  defines	
  new	
  features,	
  and	
  redefines	
  (i.e.	
  modifies)
one	
  or	
  more	
  of	
  A’s	
  features
inherits	
  from
Change	
  by	
  
Addition
Thanks	
  to	
  inheritance,	
  OO	
  developers	
  can	
  adopt	
  a	
  much	
  more	
  
incremental	
  approach	
  to	
  software	
  development	
  than	
  used	
  to	
  be	
  
possible	
  with	
  earlier	
  methods
OO	
  inheritance
Hacking  = Slipshod approach  to  building  and        
modifying  code
Slipshod = Done  poorly  or  too  quickly;;  careless.
The	
  Hacker
may	
  seem	
  
bad
but	
  often	
  his	
  
heart	
  is	
  pure.
He	
  sees	
  a	
  useful	
  piece	
  of	
  software,	
  which	
  is	
  almost	
  able	
  to	
  address	
  the	
  needs	
  of	
  the	
  
moment,	
  more	
  general	
  than	
  the	
  software’s	
  original	
  purpose.	
  
Hacker
Spurred	
  by	
  a	
  laudable	
  desire	
  not	
  to	
  redo	
  what	
  can	
  be	
  reused,	
  our	
  hacker	
  starts	
  
modifying	
   the	
  original	
  to	
  add	
  provisions	
   for	
  new	
  cases
solution
The	
  impulse	
  is	
  good	
  but	
  the	
  effect	
  
is	
  often	
  to	
  pollute	
  the	
  software	
  
with	
  many	
  clauses	
  of	
  the	
  form	
  
if that_special_case then…
if (<special	
  case	
  D>)
then …
if (<special	
  case	
  C>)
then …
if (<special	
  case	
  B>)
then …
if (<special	
  case	
  A>)
then …
switch
so	
  that	
  after	
  a	
  few	
  rounds	
  of	
  hacking,	
  perhaps	
  by	
  different	
  hackers,	
  
the	
  software	
  starts	
  resembling	
  a	
  chunk	
  of	
  Swiss	
  cheese	
  that	
  
has	
  been	
  left	
  outside	
  for	
  too	
  long	
  in	
  August	
  – it	
  has	
  both	
  holes	
  
and	
  growth
Hacking
Open-­Closed  Principle  =  
One	
  way	
  to	
  describe	
  the	
  OCP and	
  the	
  consequent	
  OO	
  techniques	
  is	
  to	
  think	
  of	
  them	
  
as	
  organised hacking
Hacking
The	
  organised form	
  of	
  hacking	
  will	
  enable	
  us	
  to	
  cater	
  to	
  the	
  variants	
  
without	
  affecting	
  the	
  consistency	
  of	
  the	
  original	
  version.
Inheritance
Change	
  by	
  
Modification
Change	
  by	
  
Addition
if	
  you	
  have	
  control	
  over	
  
original	
  s/w	
  and	
  
can	
  rewrite	
  it
so	
  that	
  it	
  will	
  address	
  the	
  needs
of	
  several	
  kinds	
  of	
  clients
…you	
  should	
   do	
  so
Caveats
at	
  no	
  extra	
  complication
The	
  OCP	
  principle	
  and	
  associated	
  techniques	
  are	
  intended	
  for	
  the	
  
adaptation	
  of	
  healthy	
  modules
If	
  there	
  is	
  something	
  wrong	
  
with	
  a	
  module	
  you	
  should	
  fix	
  
it…
…not	
  leave	
  the	
  original	
  alone	
  and	
  
try	
  to	
  correct	
  the	
  problem	
  in	
  the	
  
derived	
  module
Derived
Base
neither	
  OCP	
  nor	
  redefinition	
  in	
  
inheritance	
  is	
  a	
  way	
  to	
  address	
  
design	
  flaws,	
  let	
  alone	
  bugs Design	
  
Flaw
its	
  purpose,	
  its	
  entire	
  reason	
  
for	
  being,	
  is	
  to	
  reduce	
  the	
  
cost	
  of	
  change.
Question:	
  how	
  do	
  we	
  promote	
  flexibility,	
  
reliability	
  and	
  stability	
  in	
  our	
  software?
Analysability
Maintainabilit
y
Changeability Stability Testability
Flexibility
Reliability
Answer:	
  we	
  favour ‘Change	
  by	
  Addition’	
  over	
  	
  
‘Change	
  by	
  Modification’
Changeability
Stability
Flexibility
Reliability
Change	
  by	
  
Modification
Change	
  by	
  
Addition
-­‐
+ -­‐
+
How	
  do	
  we	
  achieve	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  ?Change	
  by	
  
Addition
which	
  uses	
  OO	
  inheritance
Inheritance
We	
  apply	
  the	
  Open-­‐Closed	
  Principle
multiple	
  maintenance	
  problem
Change	
  by	
  
Modification
CHANGE
solution
COPY	
  
solution
Hacker
Change	
  by	
  
Addition
OCP
solution
Chooses
Chooses
switch
The	
  Open	
  Closed	
  Principle
Part	
  2
An	
  Introduction	
  to	
  the	
  Contemporary	
  Version
©	
  2015	
  Philip	
  Schwarz
https://twitter.com/philip_schwarz
philip.johann.schwarz@gmail.com
This	
  work	
  is	
  licensed	
  under	
  a	
  Creative	
  Commons	
  Attribution-­‐NonCommercial-­‐NoDerivs 3.0	
  Unported
License.
multiple	
  maintenance	
  problem
Change	
  by	
  
Modification
CHANGE
solution
COPY	
  
solution
Hacker
Change	
  by	
  
Addition
OCP
solution
Chooses
Chooses
switch
extends
is	
  evil!!!!!
But…
extends is	
  evil!!!!!
But,	
  using	
  inheritance is	
  no	
  longer	
  the	
  main	
  approach	
  
to	
  satisfying	
  the	
  OCP
Allen	
  Holub 2004
2003
Using	
  inheritance	
  is	
  still	
  one	
  of	
  the	
  ways	
  of	
  satisfying	
  the	
  OCP,	
  
and	
  was	
  considered	
  THE approach	
  for	
  a	
  long	
  while
Why	
  extends	
  is	
  evil
1988	
  -­‐ 1st ed.	
   1997	
  – 2nd ed.	
  
1995	
  
That	
  started	
  changing	
  with	
  the	
  	
  emergence	
  of	
  the	
  
design	
  techniques	
  presented	
  in	
  Design	
  Patterns
2003
2004
“One	
  major	
  value	
  of	
  studying	
  patterns	
  is	
  that	
  
they	
  all,	
  whatever	
  else	
  is	
  true	
  about	
  them,	
  tend	
  
to	
  be	
  more	
  open-­‐closed than	
  the	
  alternatives”
2008 1995	
  
An	
  object's	
  class defines	
  how	
  the	
  object	
  is	
  implemented
(state and	
  operation implementation)
It's	
  important	
  to	
  understand	
  the	
  difference	
  
between	
  an	
  object's	
  class and	
  its	
  type
An	
  object's	
  type only	
  refers	
  to	
  its	
  interface -­‐
the	
  set	
  of	
  requests	
  to	
  which	
  it	
  can	
  respond
Of	
  course,	
  there	
  is	
  a	
  close	
  relationship	
  between	
  class and	
  
type.	
  Because	
  a	
  class defines	
  the	
  operations	
  it	
  can	
  
perform,	
  it	
  also	
  defines	
  the	
  object's type.
public class Person
{
private String name;
private Date birthdate;
public Person(String name, Date birthdate)
{
this.name = name;
this.birthdate = birthdate
}
public String getName() {
return name;
}
public String getBirthdate() {
return birthdate ;
}
}
Any	
  class C,	
  implicitly	
  
forms	
  a	
  type C.
Languages	
  like	
  C++	
  and	
  Eiffel	
  use	
  
classes to	
  specify	
  BOTH	
  an	
  object's	
  type
AND	
  it's	
  implementation.
An	
  object	
  can	
  have	
  many	
  types
Objects	
  of	
  different	
  classes	
  can	
  have	
  the	
  same	
  type
Generalization: a relationship
between a more specific and a
more general description, used
for inheritance and
polymorphic type
declarations
Realization: a relationship
between a specification and
its implementation
Derived	
  inherits	
  implementation from	
  Base
Derived inherits	
  type (interface)	
  from	
  Base
Derived	
  inherits	
  type	
  
from	
  Base
Current	
  and	
  future	
  specializations of	
  Base
are	
  substitutable for	
  Base in	
  clients
Current	
  and	
  future	
  realizations are	
  
substitutable for	
  Base	
  in	
  clients
“[in	
  a	
  Type	
  hierarchy]	
  the	
  supertype’s behavior	
  must	
  be	
  
supported	
  by	
  the	
  subtypes:	
  subtype	
  objects	
  can	
  be	
  
substituted	
  for	
  supertypeobjects	
  without	
  affecting	
  the	
  
behavior	
  of	
  the	
  using	
  code.”
Liskov Substitution	
   Principle	
  
(Barbara	
  Liskov – 1988)
It's	
  also	
  important	
  to	
  understand	
  the	
  difference	
  between	
  
class	
  inheritance and	
  interface	
  inheritance	
  (or	
  subtyping)	
  
In	
  contrast,	
  interface	
  inheritance	
  (or	
  subtyping)	
  describes	
  when	
  
an	
  object	
  can	
  be	
  used	
  in	
  place	
  of	
  another
Class	
  inheritance defines	
  an	
  object's	
  implementation in	
  terms	
  
of	
  another	
  object's	
  implementation.	
  In	
  short,	
  it's	
  a	
  mechanism	
  
for	
  code	
  and	
  representation	
  sharing
Class	
  Inheritance
AND Interface	
  Inheritance
JUST Interface	
  Inheritance
It's	
  easy	
  to	
  confuse	
  these	
  two	
  concepts,	
  because	
  many	
  
languages	
  don't	
  support	
  the	
  distinction between	
  [them]
In	
  languages	
  like	
  C++	
  and	
  Eiffel,	
  inheritance means	
  
BOTH interface inheritance and	
  implementation
inheritance
[	
  interface	
  inheritance and	
  implementation inheritance]
If	
  Java	
  were	
  like	
  C++,	
  it	
  would	
  only	
  support	
  realization	
  with	
  extends
Class	
  Inheritance	
  
AND Interface	
  Inheritance
JUST Interface	
  Inheritance
Most	
  statically	
  typed	
  OO	
  languages	
  conflate the	
  two	
  concerns	
  of	
  inheritance
and	
  subtyping into	
  a	
  single	
  mechanism.	
  That's	
  a	
  kludge.	
  	
  Interfaces	
  decouple	
  
the	
  two	
  concerns	
  – Nat	
  Pryce
The	
  interface construct	
  is	
  one	
  the	
  few	
  things	
  that	
  Java	
  really	
  got	
  right	
  (that	
  
and	
  GC)	
  – Steve	
  Freeman
But	
  Java	
  improves	
  on	
  C++	
  by	
  also	
  supporting	
   realization	
  with	
  implements
Class	
  Inheritance	
  
AND Interface	
  Inheritance
JUSTInterface	
  InheritanceJUSTInterface	
  Inheritance
James	
  Gosling	
  was	
  once	
  asked	
  "if	
  you	
  could	
  do	
  
java	
  over	
  again,	
  what	
  would	
  you	
  change?"
His	
  answer:	
  "I'd	
  leave	
  out	
  classes"
After	
  the	
  laughter	
  died	
  down,	
  he	
  explained	
  that	
  the	
  real	
  problem	
  wasn't	
  classes	
  
per	
  se but	
  rather	
  implementation	
  inheritance	
  (the	
  extends relationship).
Class	
  Inheritance	
  
AND Interface	
  Inheritance JUST Interface	
  InheritanceJUST Interface	
  Inheritance
Interface	
  inheritance	
  	
  (the	
  implements relationship)	
  is	
  much	
  preferred.	
  
Avoid	
  implementation	
  inheritance	
  whenever	
  possible.
Although	
   most	
  programming	
  languages	
  don't	
  support	
  
the	
  distinction	
  between	
  interface [inheritance]	
  and	
  
implementation inheritance,	
  people	
  make	
  the	
  
distinction	
  in	
  practice
Many	
  of	
  the	
  design	
  patterns	
  
Depend	
  on	
  this	
  distinction
The GoF broke the patterns into two scopes
CLASS PATTERNS
require implementation inheritance (extends) to be reified
OBJECT PATTERNS
should be implemented using nothing but interface inheritance (implements)
GoF Design Patterns
implementation
inheritance
interface
inheritance
Template	
  Method	
  Pattern
Object	
  
Modeling	
  
Technique	
  	
  
Unified	
  
Modeling	
  
Language
implementation
inheritance
Strategy	
  Pattern
OMT
UML
interface
inheritance
The	
  GoF Design	
  Patterns	
  book	
  is,	
  in	
  fact,	
  largely	
  about	
  replacing implementation	
  
inheritance	
  (extends)	
  with interface	
  inheritance (implements)
Allen	
  Holub 2004
It's	
  not	
  an	
  accident	
  that	
  there	
  are	
  many	
  more	
  Object	
  patterns	
  than	
  Class
patterns.
implementation
inheritance
interface
inheritance
Robert	
  Martin
(Uncle	
  Bob)
2002
Single	
  Responsibility	
  Principle
Open	
  Closed	
  Principle
Liskov Substitution	
  Principle
Interface	
  Segregation	
  Principle
Dependency	
  Inversion	
  Principle
Rigidity.	
  The	
  design	
  is	
  difficult	
  to	
  change.
Fragility.	
  The	
  design	
  is	
  easy	
  to	
  break.
Immobility.	
  The	
  design	
  is	
  difficult	
  to	
  reuse.
Viscosity.	
  It	
  is	
  difficult	
  to	
  do	
  the	
  right	
  thing.
Needless complexity.	
  Overdesign.
Needless repetition.	
  Mouse	
  abuse.
Opacity.	
  Disorganized	
  expression.
Symptoms of poor design (or Design Smells):
Often, the smell is caused by the violation of
one or more OO Design Principles:
OO Design Principles help developers eliminate Design Smells
The Contemporary Version of the OCP
Modules that conform to OCP have two primary attributes:
The Contemporary Version of the OCP
Robert	
  Martin
(Uncle	
  Bob)
Software entities (classes, modules, functions, etc.)
should be open for extension but closed for modification.
• They are open for extension. This means that the behavior of the module can be
extended. As the requirements of the application change, we can extend the module
with new behaviors that satisfy those changes. In other words, we are able to change
what the module does.
• They are closed for modification. Extending the behavior of a module does not
result in changes to the source, or binary, code of the module. The binary
executable version of the module…remains untouched.
The notion that a class is not coupled to another
concrete class or class that can be instantiated.
Instead, the class is coupled to other base, or
abstract, classes. Kirk	
  
Knoernschild
Account class is
coupled at the abstract
level to the
AccountType
inheritance hierarchy
So we can extend the
AccountType class, creating
a new class such as
MoneyMarket, without
having to modify our
Account class.
We have achieved OCP and now can extend our
system without modifying its existing code base.
Account isn't directly
coupled to either of the
concrete Savings or
Checking classes
2001In Java, this abstract class can be either a class
with the abstract modifier or a Java interface
data type.
At the heart of the contemporary OCP there is the
concept of abstract coupling.
Depend upon abstractions. Do not depend upon concretions.
DIP formalizes the concept of abstract coupling and clearly states that
we should couple at the abstract level, not at the concrete level
• There exists a striking similarity between DIP and OCP. In fact,
these two principles are closely related
• High-level modules should not depend on low-level
modules. Both should depend on abstractions.
DIP: The Dependency-Inversion Principle
• Abstractions should not depend on details.
Details should depend on abstractions.
• Fundamentally, DIP tells us how we can adhere to OCP
• if OCP is the desired end, DIP is the means through
which we achieve that end.
AccountType is	
  abstract,	
  so	
  the	
  coupling	
  of	
  Account to	
  
AccountType is	
  abstract	
  coupling,	
  and	
  so	
  is	
  the	
  coupling	
  of	
  
Savings and	
  Checking to	
  AccountType
High-­‐level module	
  Account does	
  not	
  depend	
  on	
  low-­‐level	
  
modules	
  Savings and	
  Checking.	
  Account,	
  Savings and	
  
Checking,	
  all	
  depend	
  on	
  an	
  abstraction:	
  AccountType.
DIP
LSP: Subclasses should be substitutable for their
base classes
Think of LSP as an extension to OCP
The	
  LSP is	
  one	
  of	
  the	
  prime	
  enablers	
  of	
  OCP
X
In	
  order	
  to	
  take	
  advantage	
  of	
  LSP,	
  
we	
  must	
  adhere	
  to	
  OCP	
  
because	
  violations	
  of	
  LSP	
  
also	
  are	
  violations	
  of	
  OCP
but	
  not	
  vice	
  versa
XX
But	
  why?
every	
  violation	
  of	
  the	
  LSP	
  is	
  a	
  latent	
  violation	
  of	
  the	
  OCP	
  
because	
  in	
  order	
  to	
  repair	
  the	
  damage …	
  we	
  are	
  going	
  to	
  have	
  
to	
  add	
  if	
  statements and	
  hang	
  dependencies	
  upon	
  subtypes
Untrustworthy	
  hierarchies [those	
  violating	
  the	
  LSP]	
  force	
  objects	
  
that	
  interact	
  with	
  them	
  to	
  know	
  their	
  quirks
when	
  asked	
  to	
  use	
  one	
  …	
  [inexperienced	
  developers]	
  will	
  embed	
  
knowledge	
  of	
  its	
  quirks	
  into	
  their	
  own	
  code	
  
if (bicycle instanceof MountainBike)
{
// do XYZ
}
if (bicycle instanceof MountainBike)
{
// do XYZ
}
if (bicycle instanceof MountainBike)
{
// code that knows about
}
often	
  by	
  explicitly	
  
checking	
  the	
  classes	
  
of	
  objects
XX
Change	
  by	
  
Modification
In its simplest form, LSP is difficult to differentiate from OCP, but a subtle difference
does exist.
Savings and	
  Checking are	
  substitutable	
  
for	
  AccountType
OCP is centered around abstract coupling. LSP, while also heavily dependent
on abstract coupling, is in addition heavily dependent on preconditions and
postconditions, which is LSP's relation to Design by Contract
LSP
Abstract coupling is
“Program	
  to	
  an	
  interface,	
  not	
  an	
  implementation”
Abstract Coupling
the means through which LSP achieves its flexibility
the mechanism required for DIP
and the heart of OCP
The	
  Template	
  Method	
  and	
  Strategy patterns	
  are	
  the	
  most	
  
common	
  ways	
  of	
  satisfying	
  OCP
Template	
  Method	
  Pattern Strategy Pattern
Is	
  one	
  as	
  good	
  as	
  the	
  other?	
  	
  Can	
  they	
  be	
  used	
  interchangeably?	
  
interface
inheritance
implementation
inheritance
“it	
  is	
  easy	
  to	
  confuse	
  implementation	
  inheritance	
  with	
  interface	
  inheritance
because	
  many	
  languages	
  don’t	
  support	
  the	
  distinction	
  between	
  them”	
  
“The	
  GoF Design	
  Patterns	
  book	
  is,	
  in	
  fact,	
  largely	
  about	
  replacing
implementation	
  inheritance	
  (extends)	
  with interface	
  
inheritance (implements)”
“Template	
  Method has	
  little	
  to	
  recommend	
  it	
  in	
  most	
  situations.	
  
Strategy for	
  example,	
  typically	
  provides	
  a	
  better	
  alternative.”
“Many	
  of	
  the	
  design	
  patterns	
  Depend	
  on	
  this	
  distinction”
Interface	
  inheritance	
  	
  (the	
  implements relationship)	
  is	
  much	
  preferred.	
  
Avoid	
  implementation	
  inheritance	
  whenever	
  possible.
“Another	
  way	
  of	
  characterizing	
  
Change	
  by	
  Addition	
  that	
  you	
  
may	
  come	
  across	
  is	
  the	
  Open	
  
Closed	
  Principle”
“Meyer is	
  generally	
  credited	
  as	
  
having	
  originated	
  the	
  term	
  
[OCP],	
   however	
  his	
  focus
(being	
  in	
  the	
  golden	
  days	
  of	
  
OO	
  inheritance)	
  was	
  on	
  the	
  
polymorphic approach”
Template	
  Method	
  Pattern
Polymorphic	
  solution
Change	
  by	
  
Addition
OCP	
  
solution
Organized	
  
Hacking
CHANGE	
  
solution
COPY	
  
solution
Source	
  code	
  copy	
  
solution
Parametric	
  
solution
multiple	
  maintenance	
  problem
Change	
  by	
  
Modification
Strategy Pattern
Compositional	
  solution
You	
  encapsulatethe	
  variability points	
  
in	
  instance	
  methods.	
  These	
  can	
  then	
  
be	
  overridden	
  in	
  subclasses,	
   one	
  for	
  
each	
  required	
  variant
You	
  encapsulate	
  the	
  variability	
  points in	
  a	
  well	
  
defined	
  interface	
  and	
  use	
  delegation to	
  compose
the	
  overall	
  behaviour.	
  Concrete	
  classes,	
  
implementing	
  the	
  interface,	
  define	
  the	
  variants’	
  
behaviour.
Change	
  by	
  
Addition
Change	
  by	
  
Addition
By	
  1995,	
  it	
  was	
  clear	
  that	
  [implementation]	
  inheritance	
  was	
  very	
  
easy	
  to	
  overuse and	
  that	
  overuse of	
  inheritance	
  was	
  very	
  costly.	
  
[The	
  Gang	
  of	
  Four]	
  went	
  so	
  far	
  as	
  to	
  stress:
[Template	
  Method and	
  Strategy are]	
  two	
  patterns	
  that	
  epitomize	
  
the	
  difference	
  between	
  inheritance and	
  delegation.	
  
They	
  solve	
  similar	
  problems	
  and	
  can	
  often	
  be	
  used	
  interchangeably
So	
  we	
  cut	
  back	
  on	
  our	
  use	
  of	
  [implementation]	
  inheritance,	
  often	
  
replacing	
  it	
  with	
  composition or	
  delegation.
“Favourobject	
  composition	
  over	
  class	
  inheritance”
Prevents	
  us	
  from	
  making	
  one	
  of	
  the	
  most	
  catastrophic	
  mistakes	
  that	
  
contribute	
  to	
  the	
  demise	
  of	
  an	
  object-­‐oriented	
  system:	
  using	
  
inheritance	
  as	
  the	
  primary	
  reuse	
  mechanism
The	
  Composite	
  Reuse	
  Principle
“These	
  two	
  patterns	
  represent	
  a	
  clear	
  separation	
  of	
  generic
functionality	
  from	
  the	
  detailed implementation of	
  that	
  
functionality”.
The	
  STRATEGYpattern	
  provides	
  one	
  extra	
  benefit	
  over	
  the	
  TEMPLATE METHODpattern.	
  
In	
  order	
  to	
  conform	
  to	
  the	
  DIP,	
  we	
  want	
  to	
  make	
  sure	
  that	
  the	
  generic algorithm
does	
  not	
  depend	
  on	
  the	
  detailed implementation.
Strategy PatternTemplate	
  Method	
  Pattern
The	
  sorting	
  algorithm	
  consists	
  of:	
  
1)	
  Generic	
  high	
  level	
  steps	
  
Can	
  be	
  used	
  to	
  sort	
  items	
  of	
  any	
  type
2)	
  Detailed	
  operations/steps
Operate	
  on	
  items	
  of	
  a	
  specific	
  type	
  
Strategy Pattern
Template	
  Method	
  Pattern
The	
  TEMPLATE METHOD pattern	
  allows	
  a	
  generic	
  algorithm	
  to	
  manipulate	
  many	
  possible	
  detailed	
  
implementations,
But	
  Template	
  Method	
  partially violates the	
  DIP	
  
because	
  it	
  uses	
  implementation	
  inheritance
so	
  the	
  detailed	
  implementations	
  
don't	
  depend	
  on	
  an	
  abstraction
they	
  depend	
  on	
  the	
  generic	
  algorithm
and	
  so	
  they	
  are	
  inextricably	
  bound	
  to	
  it	
  
and	
  cannot	
  be	
  reused	
  by	
  other	
  generic	
  algorithms
High-­‐level	
  modules	
  should	
  not	
  depend	
  on	
  
low-­‐level	
  modules.	
  
Both should	
  depend	
  on	
  abstractions.
BubbleSorter’s doSort() method	
  satisfies
the	
  DIP because	
  it	
  depends	
  on	
  abstract	
  
methods	
  outOfOrder() and	
  swap()
DoubleBubbleSorter and	
  
IntegerBubbleSorter
do	
  not	
  satisfy	
  the	
  DIP because	
  they	
  depend	
  on
BubbleSorter,	
  which	
  is	
  NOT	
  an	
  abstraction
since	
  it	
  contains	
  a	
  concrete	
  generic	
  algorithm
DIP
X
Design	
  Smell:	
  Immobility
Template	
  Method	
  Pattern
The	
  Strategy pattern	
  fully	
  conforms to	
  the	
  DIP
because	
  it	
  uses	
  interface	
  inheritance
so	
  the	
  detailed	
  implementations	
  do	
  depend	
  
on	
  an	
  abstraction(the	
  interface),	
  
so	
  the	
  detailed	
  implementations	
  can	
  be	
  manipulated	
  
by	
  (reused	
  for)	
  many	
  different	
  generic	
  algorithms
Strategy	
  has	
  this	
  additional	
  benefit	
  over	
  Template	
  Method
High-­‐level	
  modules	
  should	
  not	
  depend	
  on	
  
low-­‐level	
  modules.	
  
Both should	
  depend	
  on	
  abstractions.
DIP
Not	
  only	
  does	
  BubbleSorter
satisfy the DIP, because its
sort() method depends	
  on
interface	
  SortHandler,	
  i.e.	
  an	
  abstraction
but	
  IntegerSortHandler and	
  
DoublSortHandler
also	
  satisfy	
  the	
  DIP,	
  because	
  they	
  also	
  
depend	
  on	
  the	
  SortHandler abstraction
Strategy Pattern
inherits	
  from
(OO	
  inheritance)
Original
OCP
The	
  original	
  version	
  of	
  the	
  
OCP used	
  implementation
inheritance
While	
  the	
  contemporary	
  version	
  of	
  the	
  
OCP mostly	
  uses	
  interface inheritance,	
  
it	
  sometimes	
  does	
  use implementation
inheritance
realization
Contemporary
OCP
generalization
+
In	
  many	
  ways,	
  the	
  OCP	
  is	
  at	
  the	
  heart	
  of	
  object-­‐oriented	
  design	
  
Conformance	
  to	
  this	
  principle	
  is	
  what	
  yields	
  the	
  greatest	
  benefits	
  claimed	
  
for	
  OO	
  technology:	
  flexibility,	
  reusability,	
  and	
  maintainability
[it	
  is	
  not]	
  a	
  good	
  idea	
  to	
  apply	
  rampant	
  abstraction	
  to	
  every	
  part	
  of	
  the	
  application.	
  
Rather,	
  it	
  requires	
  a	
  dedication	
  on	
  the	
  part	
  of	
  the	
  developers	
  to	
  apply	
  abstraction	
  
only	
  to	
  those	
  parts	
  of	
  the	
  program	
  that	
  exhibit	
  frequent	
  change.	
  
Resisting	
  premature	
  abstraction	
  is	
  as	
  important	
  as	
  abstraction	
  itself.
https://cleancoders.com/episode/clean-­‐code-­‐episode-­‐10/view
References
All	
  images	
  sourced	
  from	
  http://www.google.co.uk/advanced_image_search,	
  so	
  see	
  there	
  for	
  details	
  of	
  
which	
  are	
  	
  subject	
  to	
  copyright
Object-­‐Oriented	
  Software	
  Construction	
  – by	
  Bertrand	
  Meyer;	
  Publication	
  Date:	
  3	
  April	
  1997	
  |	
  ISBN-­‐10:	
  
0136291554	
  |	
  ISBN-­‐13:	
  978-­‐0136291558	
  |	
  Edition:	
  2
Flexible,	
  Reliable	
  Software:	
  Using	
  Patterns	
  and	
  Agile	
  Development	
  – by	
  Henrik B.	
  Christensen;	
  
Publication	
  Date:	
  11	
  May	
  2010	
  |	
  ISBN-­‐10:	
  1420093622	
  |	
  ISBN-­‐13:	
  978-­‐1420093629
Design	
  Patterns	
  Explained:	
  A	
  New	
  Perspective	
  on	
  Object-­‐Oriented	
  Design;	
  by	
  Alan	
  Shalloway;	
  
Publication	
  Date:	
  12	
  Oct	
  2004	
  |	
  ISBN-­‐10:	
  0321247140	
  |	
  ISBN-­‐13:	
  978-­‐0321247148	
  |	
  Edition:	
  2
Less	
  -­‐ The	
  Path	
  to	
  Better	
  Design;	
  by	
  Sandi	
  Metz	
  at	
  GoRuCo 2011	
  goruco_2011_-­‐_sandi_metz_-­‐_less_-­‐
_the_path_to_better_design_1280x720.mp4
Why	
  Extends	
  is	
  Evil	
  -­‐ Improve	
  your	
  code	
  by	
  replacing	
  concrete	
  base	
  classes	
  with	
  interfaces;	
  by	
  
Allen	
  Holub;	
  	
  http://www.javaworld.com/article/2073649/core-­‐java/why-­‐extends-­‐is-­‐evil.html

Contenu connexe

Tendances

Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and reduxCuong Ho
 
Clean architecture
Clean architectureClean architecture
Clean architectureandbed
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Philip Schwarz
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keywordPham Huy Tung
 
Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven DevelopmentLiz Keogh
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsScott Gardner
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLIDPranalee Rokde
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipIvan Paulovich
 
Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Nelson Glauber Leal
 
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A....NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...NETFest
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 

Tendances (20)

Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven Development
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
What's new in Visual Studio 2022
What's new in Visual Studio 2022What's new in Visual Studio 2022
What's new in Visual Studio 2022
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
Solid principles
Solid principlesSolid principles
Solid principles
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
 
Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021
 
AngularJS
AngularJSAngularJS
AngularJS
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
 
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A....NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 

Similaire à The Open-Closed Principle - the Original Version and the Contemporary Version

The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionPhilip Schwarz
 
DesignPrinciples-and-DesignPatterns
DesignPrinciples-and-DesignPatternsDesignPrinciples-and-DesignPatterns
DesignPrinciples-and-DesignPatternsBasavaraj Patil
 
Practical Enterprise Application Development
Practical Enterprise Application DevelopmentPractical Enterprise Application Development
Practical Enterprise Application DevelopmentAdil Mughal
 
Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desaijinaldesailive
 
Chapter 3 Software Process Model.ppt
Chapter 3 Software Process Model.pptChapter 3 Software Process Model.ppt
Chapter 3 Software Process Model.pptRayonJ1
 
Software Process Model in software engineering
Software Process Model in software engineeringSoftware Process Model in software engineering
Software Process Model in software engineeringMuhammadTalha436
 
Software development process models
Software development process modelsSoftware development process models
Software development process modelsMuntha Ulfat
 
Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Kuwait10
 
Test Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, MockingTest Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, Mockingmrjawright
 
System design process.pptx
System design process.pptxSystem design process.pptx
System design process.pptxNajibMuhammad16
 
Software Architecture for Agile Development
Software Architecture for Agile DevelopmentSoftware Architecture for Agile Development
Software Architecture for Agile DevelopmentHayim Makabee
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionKnoldus Inc.
 
Code Craftsmanship Checklist
Code Craftsmanship ChecklistCode Craftsmanship Checklist
Code Craftsmanship ChecklistRyan Polk
 
Software Development Standard Operating Procedure
Software Development Standard Operating Procedure Software Development Standard Operating Procedure
Software Development Standard Operating Procedure rupeshchanchal
 

Similaire à The Open-Closed Principle - the Original Version and the Contemporary Version (20)

The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original Version
 
Solid
SolidSolid
Solid
 
DesignPrinciples-and-DesignPatterns
DesignPrinciples-and-DesignPatternsDesignPrinciples-and-DesignPatterns
DesignPrinciples-and-DesignPatterns
 
Soild principles
Soild principlesSoild principles
Soild principles
 
Practical Enterprise Application Development
Practical Enterprise Application DevelopmentPractical Enterprise Application Development
Practical Enterprise Application Development
 
Software process model
Software process modelSoftware process model
Software process model
 
Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desai
 
Software Engineering CSE/IT.pptx
 Software Engineering CSE/IT.pptx Software Engineering CSE/IT.pptx
Software Engineering CSE/IT.pptx
 
Chapter 3 Software Process Model.ppt
Chapter 3 Software Process Model.pptChapter 3 Software Process Model.ppt
Chapter 3 Software Process Model.ppt
 
Software Process Model in software engineering
Software Process Model in software engineeringSoftware Process Model in software engineering
Software Process Model in software engineering
 
Software development process models
Software development process modelsSoftware development process models
Software development process models
 
Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10
 
Test Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, MockingTest Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, Mocking
 
reaserch ppt.pptx
reaserch ppt.pptxreaserch ppt.pptx
reaserch ppt.pptx
 
System design process.pptx
System design process.pptxSystem design process.pptx
System design process.pptx
 
Software Architecture for Agile Development
Software Architecture for Agile DevelopmentSoftware Architecture for Agile Development
Software Architecture for Agile Development
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test Automaion
 
Code Craftsmanship Checklist
Code Craftsmanship ChecklistCode Craftsmanship Checklist
Code Craftsmanship Checklist
 
Software Development Standard Operating Procedure
Software Development Standard Operating Procedure Software Development Standard Operating Procedure
Software Development Standard Operating Procedure
 
android principle.pptx
android principle.pptxandroid principle.pptx
android principle.pptx
 

Plus de Philip Schwarz

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesPhilip Schwarz
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesPhilip Schwarz
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesPhilip Schwarz
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three ApproachesPhilip Schwarz
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsPhilip Schwarz
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaPhilip Schwarz
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaPhilip Schwarz
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaPhilip Schwarz
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsPhilip Schwarz
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Philip Schwarz
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...Philip Schwarz
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an examplePhilip Schwarz
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an examplePhilip Schwarz
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...Philip Schwarz
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...Philip Schwarz
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsPhilip Schwarz
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Philip Schwarz
 
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Philip Schwarz
 

Plus de Philip Schwarz (20)

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a series
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a series
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a series
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with Views
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in Scala
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in Scala
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axioms
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
 
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
 

Dernier

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Dernier (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

The Open-Closed Principle - the Original Version and the Contemporary Version

  • 1.
  • 2. The  Open  Closed  Principle Part  I The  Original  Version ©  2014  Philip  Schwarz https://twitter.com/philip_schwarz philip.johann.schwarz@gmail.com This  work  is  licensed  under  a  Creative  Commons  Attribution-­‐NonCommercial-­‐NoDerivs 3.0  Unported License.
  • 3. Tension  Between known   needs   of  today changes  that   will  arrive  in   the  future Sandi  Metz The  Fundamental  Target  of   Design
  • 4. Code  needs  to   work  today  just   once, and  it  needs  to  be  easy  to  change  forever
  • 5. It  is  at  this  point  of  tension where  design  matters today’s needs   future changes
  • 6. its  purpose,  its  entire  reason   for  being,  is  to  reduce  the   cost  of  change.
  • 7. 1999 3rd Apr  2014   @KentBeck design is  irrelevant  for  today.  it  only  matters  when  we  want  to  change  the   software... @KentBeck change  is  the  only  reason  to  organize  software  at  all… Kent  Beck
  • 8. adopted  by  agile   community  as  a  truth   about  software   development Henrik Christensen 2010
  • 9. “software  must  be  designed  and  developed  to   make  it  easy  to  change”
  • 10. Let’s  examine  software  qualities  that  enable ease  of  change   Look  for  definitions  in  ISO  9126 Projects  sometimes  fail due  to  not  having  any  clear   definitions  of  "success” This  standard  tries  to  develop  a  common  understanding  of   project  objectives  and  goals,  e.g.  software  qualities
  • 11. Software  is  Reliabile if  it  can  maintain  a   specific  level  of  performance under  specific   usage  conditions
  • 12. in  our   setting… In  particular,  we  are  interested  in preserving  reliability  in  the  face  of  change   Software  is  Reliabile if  it  can  perform  the   required  functions  without  failing  
  • 13. “maintainability is  composed  of   several,  finer  grained,  qualities”
  • 14. Analysability Maintainability Changeability Stability Testability Software  is  Analysable if  you  can • diagnose  it  for   § deficiencies § causes  of  failure • identify  the  parts  to  be  modified “Analysability is  basically  the  ability  to  understand software”
  • 15. Analysability Maintainability Changeability Stability Testability Software  is  changeable  if  it  allows  you  to • implement  a  specific  modification • add,  modify,  or  enhance  a  feature   at  a  reasonable  cost “almost  all  Design  Patterns are   geared  towards  increasing   design’s  changeability”
  • 16. Analysability Maintainability Changeability Stability Testability “Software  is  flexible  if  you  can  add/enhance     functionality  purely  by  adding  software units   and  specifically  not  by  modifying  existing   software  units” Flexibility a  special  case  of   changeability
  • 17. Changeability Behavioural changes  that  are  introduced   by  modifying existing  production  code Changeability  is  a  desirable  quality,   but it  relies  on Change  by  Modification Change  by   Modification “The  less  I  ever  modify  a  class,  the  higher  the  probability  that   it  will  remain  free  of  defects” Modifications  carry  the  risk  of  introducing  defects,  and  the   necessary  cost  of  avoiding  them:  testing,  code  reviewing,  etc.
  • 18. Behavioural changes  that  are  introduced   by  modifying existing  production  code Change  by   Modification Change  by   Addition Behavioural changes  that  are  introduced  by   adding new  production  code  instead  of   modifying  existing  code Contrast   Change  by  Addition  avoids  (risky)  modifications  altogether with
  • 19. Changeability Change  by   Addition Change  by   Modification Changeability  does  not  take  a  stand  point  with  regards   to  the  way  a  specified  modification  is  implemented Flexibility In  contrast,  Flexibility  does  take  this  stand  point   and  requires  that  no  modifications  are  made
  • 20. Analysability Maintainability Changeability Stability Testability Software  is  Stable  if  it  avoids  unexpected  effects  when   modified “I  advocate  the  practice  to  avoid  modifying  existing  code  but   preferably  add  features  or  modify  existing  ones by  other   means” Flexibility “any  change  to  existing  software  carries  a  risk  of  introducing   defects”
  • 21. Changeability Stability Flexibility Reliability Change  by   Modification Change  by   Addition -­‐ + -­‐ + Summary + supports -­‐ risks  undermining relies  on
  • 22. Question:  how  do  we  promote  flexibility,   reliability  and  stability  in  our  software? Analysability Maintainability Changeability Stability Testability Flexibility Reliability
  • 23. Answer:  we  favour ‘Change  by  Addition’  over     ‘Change  by  Modification’ Changeability Stability Flexibility Reliability Change  by   Modification Change  by   Addition -­‐ + -­‐ +
  • 24. I  cover  techniques  that   focus  on  flexibility   Christensen if  you  require   that  s/w  can   adapt  to   changing   requirements without   modifying   the   production   code then  you  need  to   employ  a  SPECIAL   set  of  design  and   programming   techniques  as  well   as  adopt  a   SPECIAL  mindset
  • 25. “Another  way  of  characterising Change  by  Addition  that  you  may   come  across  is  the  Open  Closed   Principle” How  do  we  achieve                                                                    ?Change  by   Addition
  • 26. The  Open-­‐Closed  Principle Modules  should  be  both  open  and  closed Bertrand  Meyer Object  Oriented   Software  Construction The  most  comprehensive,   definitive   OO  reference  ever  published1988
  • 27. Isn’t  there  a  contradiction between  the  two  terms? Modules  should  be  both   OPEN  and  CLOSED ¬(p  ∧ ¬p)  
  • 28. The contradiction  is  only  apparent The  two  terms   correspond  to   goals  of  a   different  nature e.g.  a  Dutch  door  can  be   both OPEN  and CLOSED It  is  a  
  • 29. So  let’s  look  at  the  goals  of  the  OCP OCP
  • 30. A  module  is   said  to  be   OPEN if  it  is  still   available  for   extension or  add fields to  its  data   structures Data  Structures fields + operations e.g.  it  should  be  possible  to   expand its  set  of  operations  
  • 31. A  module  is   said  to  be   CLOSED If  it  is  available   for  use by   other  modules Has  a  well-­‐defined,  stable description   (its  interface – in  information  hiding   sense) public  part secret  part interface 1 can  be  compiled,   stored  in  a  library,  and  made   available  for  clients  to  use2 in  the  case  of  a  design  or  specification  module: • approved • baselined in  version  control • its  interface  published    for  benefit  of  other  module  authors 3
  • 32. OPEN if  it  is  still   available  for   extension CLOSED If  it  is  available   for  use by   other  modules Recap  – A  module  is…
  • 33. It  is  impossible  to  foresee  all  the  elements   that  a  module  will  need  in  its  lifetime X The  need  for     ness so  developers  wish  to  keep  the  module  open  for  as  long  as  possible so  that  they  can  address  changes,   and  extensions   by  changing  elements  or   adding  new  elements
  • 34. The  need  for     ness if  a  module  is  never  closed  until  it  is  certain   that  it  contains  all  the  needed  features   x every  developer  would  always  be  waiting  for   completion  of  another  developer's  job then  multi-­‐module   s/w  can   never  reach  completionx in  a  system  consisting  of  many  modules,   most   modules  will  depend  on  some  others but  it  is  also  necessary  to  close  modules
  • 35. Modules  should  be  both  open  and  closed We  want  modules  to  be  both                                  for  extension  and                              for  modification
  • 36. the  two  goals  of   openness  and  closedness with  traditional   techniques are  incompatible
  • 37. either  you  keep  a  module  open   and  others  cannot  use  it  yet and  any  change  or   extension  can  trigger  a   painful  chain  reaction  of   changes or  you  close  it   in  many  other  modules   which  relied  on  the   original  module  directly   or  indirectly
  • 38. AB C D E A  module  and  its  clients A’F G H I New  clients  which  need  A’,  an  adapted  or  extended  version  of  A Typical  situation  where  the  needs  for  Open  and  Closed   modules  are  hard  to  reconcile =    client  of
  • 39. With  non-­‐OO  methods,   there  seem  to  be  only  2  solutions,   equally  unsatisfactory
  • 40. AB C D E AF G H I Solution  1
  • 41. AB C D E AF G H I Solution  1
  • 42. AB C D E A’F G H I Solution We  have  taken  a  copy  of  A  and  modified   it,  turning   it  into  the  desired  A’
  • 43. Solution Meyer’s  Assessment the  consequences  are  appalling an  explosion  of  variants of  the  original  module,   many  of  them  very  similar, but  never  quite  identical if  you  extrapolate  its  effects  to   • many modules   • many modification  requests   • a  long period  of  time
  • 44. Solution  (Source  tree  copy) Christensen’s  Assessment Probably  the  main  reason  it  is  encountered  so  often  in  practice Easy  to  explain  to  colleagues  &  new  developers   No  implementation  interferenceX
  • 45. Solution  (Source  tree  copy) Christensen’s  Assessment Quick  but  very  dangerous In  the  long  run  it  is   often  a  real  disaster… The  solution  has  severe   limitations.  
  • 46. because  it  leads  to  the multiple  maintenance  problem
  • 47. Solution  (Source  tree  copy) Christensen’s  Assessment when  you  want  to  add/modify  logic   you  have  to: • Do  it  for  each  source  tree • Write  the  same  test  cases  for  each   source  tree you  have  to  do  it  in   each  source  tree when  you  need  to   remove  a  defect  
  • 48. DRIFT Practice  shows  that  over  time  the   source  trees  evolve  into  completely   different  directions:  they  drift  apart. After  a  while  it  is  more  or   less  like  maintaining a  set   of  completely  different   applications At  that  point,  before  you  do  any  of   the  operations,  you  have  to  first   analyse each source  tree!!
  • 49. Used  in  airports  to  generate  reports  of  local  weather one  variant  for  each  airport  in  Denmark init and  config code Example SAWOS -­‐ Semi  Automatic  Weather  Observation  System 8  copies!!!
  • 50. Analysability Stability Reliability solution -­‐ -­‐ -­‐ Summary multiple  maintenance  problem
  • 51. That  was  Meyer’s  first  unsatisfactory solution to  the  problem  of  making  modules   both  OPEN  and  CLOSED Let’s  turn  to  the  second  one
  • 52. AB C D E A’F G H I A  module  and  its  clients New  clients  which  need  A’,  an  adapted  or  extended  version  of  A =    client  of Problem
  • 53. Solution  2 AB C D E A’F G H I Change  by   Modification
  • 54. A+B C D E A’F G H I We  have  modified   A  into  A+,  which  can  switch  between  two  modes  of  execution In  one  mode  it  behaves  like  A,  and  in  the  other  it  behaves  as  expected  of  A’   Solution
  • 55. A+B C D E A’F G H I We  have  modified   A  into  A+,  which  can  switch  between  two  modes  of  execution In  one  mode  it  behaves  like  A,  and  in  the  other  it  behaves  as  expected  of  A’   Solution
  • 56. A+B C D E A’F G H I if  (variant  ==  VARIANT_1) then  { ….   }  else  { …. }   At  points  of  variation,  A+  looks  like  this: We  have  modified   A  into  A+,  which  can  switch  between  two  modes  of  execution In  one  mode  it  behaves  like  A,  and  in  the  other  it  behaves  as  expected  of  A’   Alternatively,  this  can   be  a  switch Solution
  • 57. A+B C D E A’F G H I Solution  – Meyer’s  Assessment
  • 58. A+B C D E A’F G H I The  potential  for  disaster is  obvious:   changes  to  A  may  invalidate  the  assumptions  on  the   basis  of  which  the  old  clients  used  A. So  the  changes  may  start  a  dramatic  series  of  changes  in  clients,  client  of  clients....etc Solution  – Meyer’s  Assessment
  • 59. A+ A’F G H I Solution  – Meyer’s  Assessment The  potential  for  disaster  is  obvious:   changes  to  A  may  invalidate  the  assumptions  on  the   basis  of  which  the  old  clients  used  A. So  the  changes  may  start  a  dramatic  series  of  changes  in  clients,  client  of  clients....etc B C E D this  is  a  nightmare  for  the  proj.  mgr. the  system  regresses and  several  modules   have  to  be  re-­‐ opened  for   dev/test/debug/documentation
  • 60. Even  though   the  Change  solution  has  this  problematic  ripple  effect,  it  is  still  better  than   the  Copy  solution. On  the  surface,  the  copy  solution  seems  better  because  it  avoids  the  ripple  effect  of  change but  in  fact  it  may  even  be  more  catastrophic…it  only  postpones   the  day  of  reckoning We  saw  earlier  the  risks  of  an  explosion  of  variants,  many  of  them  very  similar,   but  never  quite  identical: Solution  – Meyer’s  Assessment solutionsolution
  • 61. Solution  (Parametric  solution) Christensen’s  Assessment Conditionals  are  easy  to  understand.  So  approach  is  easy  to   describe  to  other  developers. Avoids  Multiple  Maintenance  Problem   Only  one  code  base  to  maintain solutionsolution
  • 62. Liabilities,  most  of  which  deal  with  long  term  maintainability Change  by   Modification Reliability  Concerns  – solution  relies  on     with  risk  of   introducing   new  defects Analysability concerns  – as  more  and  more   requirements  are  handled  by  parameter   switching,  the  code  becomes  less  easy  to   analyse … Responsibility  erosion  – the  software  has,   without  much  notice,  been  given  an  extra   responsibility drives   towards Procedural Design Blob  aka God  Class Solution  (Parametric  solution) Christensen’s  Assessment
  • 63. A  reasonable  approach  at  first,  but  one  with  serious  problems for  applications  that  need  to  grow  over  time Solution  (Switches) Shalloway’s Assessment Not  too  bad  as  long  as  you  just  keep  adding  cases… 2004
  • 64. but  soon  you  need  to  introduce  fall-­‐throughs… …and  then  the  switches  are  not  as  nice  as  they  used  to  be
  • 65. Eventually  you  need  to  start  adding  variations  within  a  case.   I  like  to  call  this   switch The  flow  of  the  switches  themselves  becomes  confusing,  hard  to  read,  hard  to   decipher. When  a  new  case  comes  in  the  programmer  must  find  every  place  it  can   be  involved  (often  finding  all  but  one  of  them). Suddenly   things  get  bad  in  a  hurry.  
  • 66. Analysability Stability Reliability solution -­‐ -­‐ -­‐ Summary Analysability Stability Reliability solution -­‐ -­‐ -­‐ With  non-­‐OO  methods,  there  are  only  only  2  solutions  available  to  us,   BOTH  UNSATISFACTORY multiple  maintenance  problem Change  by   Modification CHANGE COPY
  • 67. If  non-­‐OO  methods  are  all  we  have,  then   Meyer  says  we  face  a  change  or  copy   dilemma CHANGE COPY
  • 68. AB C D E A’F G H I So  how  can  we  have  modules  that  are  both                                and                                    ? How  can  we  keep  A  and  everything  in  the  top  part  of  the  figure  unchanged,  … …while  providing   A’  to  the  bottom  clients,  and  avoiding  duplication  of  software?  
  • 69. AB C D E A’F G H I With  the  OO  concept  of  inheritance Inheritance  allows  us  to  get  out  of  the  CHANGE  OR  COPY  dilemma… …because  inheritance  allows  us  to  define  a  new  module  A'  in  terms  of  an  existing   module  A,  …by  stating  only  the  differences  between  the  two   A’  defines  new  features,  and  redefines  (i.e.  modifies) one  or  more  of  A’s  features inherits  from Change  by   Addition
  • 70. Thanks  to  inheritance,  OO  developers  can  adopt  a  much  more   incremental  approach  to  software  development  than  used  to  be   possible  with  earlier  methods OO  inheritance
  • 71. Hacking  = Slipshod approach  to  building  and         modifying  code Slipshod = Done  poorly  or  too  quickly;;  careless. The  Hacker may  seem   bad but  often  his   heart  is  pure.
  • 72. He  sees  a  useful  piece  of  software,  which  is  almost  able  to  address  the  needs  of  the   moment,  more  general  than  the  software’s  original  purpose.   Hacker Spurred  by  a  laudable  desire  not  to  redo  what  can  be  reused,  our  hacker  starts   modifying   the  original  to  add  provisions   for  new  cases solution
  • 73. The  impulse  is  good  but  the  effect   is  often  to  pollute  the  software   with  many  clauses  of  the  form   if that_special_case then… if (<special  case  D>) then … if (<special  case  C>) then … if (<special  case  B>) then … if (<special  case  A>) then … switch
  • 74. so  that  after  a  few  rounds  of  hacking,  perhaps  by  different  hackers,   the  software  starts  resembling  a  chunk  of  Swiss  cheese  that   has  been  left  outside  for  too  long  in  August  – it  has  both  holes   and  growth Hacking
  • 75. Open-­Closed  Principle  =   One  way  to  describe  the  OCP and  the  consequent  OO  techniques  is  to  think  of  them   as  organised hacking Hacking The  organised form  of  hacking  will  enable  us  to  cater  to  the  variants   without  affecting  the  consistency  of  the  original  version. Inheritance Change  by   Modification Change  by   Addition
  • 76. if  you  have  control  over   original  s/w  and   can  rewrite  it so  that  it  will  address  the  needs of  several  kinds  of  clients …you  should   do  so Caveats at  no  extra  complication
  • 77. The  OCP  principle  and  associated  techniques  are  intended  for  the   adaptation  of  healthy  modules If  there  is  something  wrong   with  a  module  you  should  fix   it… …not  leave  the  original  alone  and   try  to  correct  the  problem  in  the   derived  module Derived Base neither  OCP  nor  redefinition  in   inheritance  is  a  way  to  address   design  flaws,  let  alone  bugs Design   Flaw
  • 78.
  • 79. its  purpose,  its  entire  reason   for  being,  is  to  reduce  the   cost  of  change.
  • 80. Question:  how  do  we  promote  flexibility,   reliability  and  stability  in  our  software? Analysability Maintainabilit y Changeability Stability Testability Flexibility Reliability
  • 81. Answer:  we  favour ‘Change  by  Addition’  over     ‘Change  by  Modification’ Changeability Stability Flexibility Reliability Change  by   Modification Change  by   Addition -­‐ + -­‐ +
  • 82. How  do  we  achieve                                                                    ?Change  by   Addition which  uses  OO  inheritance Inheritance We  apply  the  Open-­‐Closed  Principle
  • 83. multiple  maintenance  problem Change  by   Modification CHANGE solution COPY   solution Hacker Change  by   Addition OCP solution Chooses Chooses switch
  • 84.
  • 85. The  Open  Closed  Principle Part  2 An  Introduction  to  the  Contemporary  Version ©  2015  Philip  Schwarz https://twitter.com/philip_schwarz philip.johann.schwarz@gmail.com This  work  is  licensed  under  a  Creative  Commons  Attribution-­‐NonCommercial-­‐NoDerivs 3.0  Unported License.
  • 86. multiple  maintenance  problem Change  by   Modification CHANGE solution COPY   solution Hacker Change  by   Addition OCP solution Chooses Chooses switch extends is  evil!!!!! But…
  • 87. extends is  evil!!!!! But,  using  inheritance is  no  longer  the  main  approach   to  satisfying  the  OCP Allen  Holub 2004 2003
  • 88. Using  inheritance  is  still  one  of  the  ways  of  satisfying  the  OCP,   and  was  considered  THE approach  for  a  long  while Why  extends  is  evil 1988  -­‐ 1st ed.   1997  – 2nd ed.   1995   That  started  changing  with  the    emergence  of  the   design  techniques  presented  in  Design  Patterns 2003 2004
  • 89. “One  major  value  of  studying  patterns  is  that   they  all,  whatever  else  is  true  about  them,  tend   to  be  more  open-­‐closed than  the  alternatives” 2008 1995  
  • 90. An  object's  class defines  how  the  object  is  implemented (state and  operation implementation) It's  important  to  understand  the  difference   between  an  object's  class and  its  type An  object's  type only  refers  to  its  interface -­‐ the  set  of  requests  to  which  it  can  respond
  • 91. Of  course,  there  is  a  close  relationship  between  class and   type.  Because  a  class defines  the  operations  it  can   perform,  it  also  defines  the  object's type. public class Person { private String name; private Date birthdate; public Person(String name, Date birthdate) { this.name = name; this.birthdate = birthdate } public String getName() { return name; } public String getBirthdate() { return birthdate ; } } Any  class C,  implicitly   forms  a  type C. Languages  like  C++  and  Eiffel  use   classes to  specify  BOTH  an  object's  type AND  it's  implementation.
  • 92. An  object  can  have  many  types Objects  of  different  classes  can  have  the  same  type
  • 93. Generalization: a relationship between a more specific and a more general description, used for inheritance and polymorphic type declarations Realization: a relationship between a specification and its implementation Derived  inherits  implementation from  Base Derived inherits  type (interface)  from  Base Derived  inherits  type   from  Base Current  and  future  specializations of  Base are  substitutable for  Base in  clients Current  and  future  realizations are   substitutable for  Base  in  clients “[in  a  Type  hierarchy]  the  supertype’s behavior  must  be   supported  by  the  subtypes:  subtype  objects  can  be   substituted  for  supertypeobjects  without  affecting  the   behavior  of  the  using  code.” Liskov Substitution   Principle   (Barbara  Liskov – 1988)
  • 94. It's  also  important  to  understand  the  difference  between   class  inheritance and  interface  inheritance  (or  subtyping)   In  contrast,  interface  inheritance  (or  subtyping)  describes  when   an  object  can  be  used  in  place  of  another Class  inheritance defines  an  object's  implementation in  terms   of  another  object's  implementation.  In  short,  it's  a  mechanism   for  code  and  representation  sharing Class  Inheritance AND Interface  Inheritance JUST Interface  Inheritance
  • 95. It's  easy  to  confuse  these  two  concepts,  because  many   languages  don't  support  the  distinction between  [them] In  languages  like  C++  and  Eiffel,  inheritance means   BOTH interface inheritance and  implementation inheritance [  interface  inheritance and  implementation inheritance]
  • 96. If  Java  were  like  C++,  it  would  only  support  realization  with  extends Class  Inheritance   AND Interface  Inheritance JUST Interface  Inheritance
  • 97. Most  statically  typed  OO  languages  conflate the  two  concerns  of  inheritance and  subtyping into  a  single  mechanism.  That's  a  kludge.    Interfaces  decouple   the  two  concerns  – Nat  Pryce The  interface construct  is  one  the  few  things  that  Java  really  got  right  (that   and  GC)  – Steve  Freeman But  Java  improves  on  C++  by  also  supporting   realization  with  implements Class  Inheritance   AND Interface  Inheritance JUSTInterface  InheritanceJUSTInterface  Inheritance
  • 98. James  Gosling  was  once  asked  "if  you  could  do   java  over  again,  what  would  you  change?" His  answer:  "I'd  leave  out  classes" After  the  laughter  died  down,  he  explained  that  the  real  problem  wasn't  classes   per  se but  rather  implementation  inheritance  (the  extends relationship). Class  Inheritance   AND Interface  Inheritance JUST Interface  InheritanceJUST Interface  Inheritance Interface  inheritance    (the  implements relationship)  is  much  preferred.   Avoid  implementation  inheritance  whenever  possible.
  • 99. Although   most  programming  languages  don't  support   the  distinction  between  interface [inheritance]  and   implementation inheritance,  people  make  the   distinction  in  practice Many  of  the  design  patterns   Depend  on  this  distinction
  • 100. The GoF broke the patterns into two scopes CLASS PATTERNS require implementation inheritance (extends) to be reified OBJECT PATTERNS should be implemented using nothing but interface inheritance (implements)
  • 102. Template  Method  Pattern Object   Modeling   Technique     Unified   Modeling   Language implementation inheritance
  • 104. The  GoF Design  Patterns  book  is,  in  fact,  largely  about  replacing implementation   inheritance  (extends)  with interface  inheritance (implements) Allen  Holub 2004 It's  not  an  accident  that  there  are  many  more  Object  patterns  than  Class patterns. implementation inheritance interface inheritance
  • 105. Robert  Martin (Uncle  Bob) 2002 Single  Responsibility  Principle Open  Closed  Principle Liskov Substitution  Principle Interface  Segregation  Principle Dependency  Inversion  Principle Rigidity.  The  design  is  difficult  to  change. Fragility.  The  design  is  easy  to  break. Immobility.  The  design  is  difficult  to  reuse. Viscosity.  It  is  difficult  to  do  the  right  thing. Needless complexity.  Overdesign. Needless repetition.  Mouse  abuse. Opacity.  Disorganized  expression. Symptoms of poor design (or Design Smells): Often, the smell is caused by the violation of one or more OO Design Principles: OO Design Principles help developers eliminate Design Smells The Contemporary Version of the OCP
  • 106. Modules that conform to OCP have two primary attributes: The Contemporary Version of the OCP Robert  Martin (Uncle  Bob) Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. • They are open for extension. This means that the behavior of the module can be extended. As the requirements of the application change, we can extend the module with new behaviors that satisfy those changes. In other words, we are able to change what the module does. • They are closed for modification. Extending the behavior of a module does not result in changes to the source, or binary, code of the module. The binary executable version of the module…remains untouched.
  • 107. The notion that a class is not coupled to another concrete class or class that can be instantiated. Instead, the class is coupled to other base, or abstract, classes. Kirk   Knoernschild Account class is coupled at the abstract level to the AccountType inheritance hierarchy So we can extend the AccountType class, creating a new class such as MoneyMarket, without having to modify our Account class. We have achieved OCP and now can extend our system without modifying its existing code base. Account isn't directly coupled to either of the concrete Savings or Checking classes 2001In Java, this abstract class can be either a class with the abstract modifier or a Java interface data type. At the heart of the contemporary OCP there is the concept of abstract coupling.
  • 108. Depend upon abstractions. Do not depend upon concretions. DIP formalizes the concept of abstract coupling and clearly states that we should couple at the abstract level, not at the concrete level • There exists a striking similarity between DIP and OCP. In fact, these two principles are closely related • High-level modules should not depend on low-level modules. Both should depend on abstractions. DIP: The Dependency-Inversion Principle • Abstractions should not depend on details. Details should depend on abstractions. • Fundamentally, DIP tells us how we can adhere to OCP • if OCP is the desired end, DIP is the means through which we achieve that end.
  • 109. AccountType is  abstract,  so  the  coupling  of  Account to   AccountType is  abstract  coupling,  and  so  is  the  coupling  of   Savings and  Checking to  AccountType High-­‐level module  Account does  not  depend  on  low-­‐level   modules  Savings and  Checking.  Account,  Savings and   Checking,  all  depend  on  an  abstraction:  AccountType. DIP
  • 110. LSP: Subclasses should be substitutable for their base classes Think of LSP as an extension to OCP The  LSP is  one  of  the  prime  enablers  of  OCP X In  order  to  take  advantage  of  LSP,   we  must  adhere  to  OCP   because  violations  of  LSP   also  are  violations  of  OCP but  not  vice  versa XX But  why?
  • 111. every  violation  of  the  LSP  is  a  latent  violation  of  the  OCP   because  in  order  to  repair  the  damage …  we  are  going  to  have   to  add  if  statements and  hang  dependencies  upon  subtypes Untrustworthy  hierarchies [those  violating  the  LSP]  force  objects   that  interact  with  them  to  know  their  quirks when  asked  to  use  one  …  [inexperienced  developers]  will  embed   knowledge  of  its  quirks  into  their  own  code   if (bicycle instanceof MountainBike) { // do XYZ } if (bicycle instanceof MountainBike) { // do XYZ } if (bicycle instanceof MountainBike) { // code that knows about } often  by  explicitly   checking  the  classes   of  objects XX Change  by   Modification
  • 112. In its simplest form, LSP is difficult to differentiate from OCP, but a subtle difference does exist. Savings and  Checking are  substitutable   for  AccountType OCP is centered around abstract coupling. LSP, while also heavily dependent on abstract coupling, is in addition heavily dependent on preconditions and postconditions, which is LSP's relation to Design by Contract LSP
  • 113. Abstract coupling is “Program  to  an  interface,  not  an  implementation” Abstract Coupling the means through which LSP achieves its flexibility the mechanism required for DIP and the heart of OCP
  • 114. The  Template  Method  and  Strategy patterns  are  the  most   common  ways  of  satisfying  OCP Template  Method  Pattern Strategy Pattern Is  one  as  good  as  the  other?    Can  they  be  used  interchangeably?   interface inheritance implementation inheritance
  • 115. “it  is  easy  to  confuse  implementation  inheritance  with  interface  inheritance because  many  languages  don’t  support  the  distinction  between  them”   “The  GoF Design  Patterns  book  is,  in  fact,  largely  about  replacing implementation  inheritance  (extends)  with interface   inheritance (implements)” “Template  Method has  little  to  recommend  it  in  most  situations.   Strategy for  example,  typically  provides  a  better  alternative.” “Many  of  the  design  patterns  Depend  on  this  distinction” Interface  inheritance    (the  implements relationship)  is  much  preferred.   Avoid  implementation  inheritance  whenever  possible.
  • 116. “Another  way  of  characterizing   Change  by  Addition  that  you   may  come  across  is  the  Open   Closed  Principle” “Meyer is  generally  credited  as   having  originated  the  term   [OCP],   however  his  focus (being  in  the  golden  days  of   OO  inheritance)  was  on  the   polymorphic approach” Template  Method  Pattern Polymorphic  solution Change  by   Addition OCP   solution Organized   Hacking CHANGE   solution COPY   solution Source  code  copy   solution Parametric   solution multiple  maintenance  problem Change  by   Modification Strategy Pattern Compositional  solution You  encapsulatethe  variability points   in  instance  methods.  These  can  then   be  overridden  in  subclasses,   one  for   each  required  variant You  encapsulate  the  variability  points in  a  well   defined  interface  and  use  delegation to  compose the  overall  behaviour.  Concrete  classes,   implementing  the  interface,  define  the  variants’   behaviour. Change  by   Addition Change  by   Addition
  • 117. By  1995,  it  was  clear  that  [implementation]  inheritance  was  very   easy  to  overuse and  that  overuse of  inheritance  was  very  costly.   [The  Gang  of  Four]  went  so  far  as  to  stress: [Template  Method and  Strategy are]  two  patterns  that  epitomize   the  difference  between  inheritance and  delegation.   They  solve  similar  problems  and  can  often  be  used  interchangeably So  we  cut  back  on  our  use  of  [implementation]  inheritance,  often   replacing  it  with  composition or  delegation. “Favourobject  composition  over  class  inheritance” Prevents  us  from  making  one  of  the  most  catastrophic  mistakes  that   contribute  to  the  demise  of  an  object-­‐oriented  system:  using   inheritance  as  the  primary  reuse  mechanism The  Composite  Reuse  Principle
  • 118. “These  two  patterns  represent  a  clear  separation  of  generic functionality  from  the  detailed implementation of  that   functionality”. The  STRATEGYpattern  provides  one  extra  benefit  over  the  TEMPLATE METHODpattern.   In  order  to  conform  to  the  DIP,  we  want  to  make  sure  that  the  generic algorithm does  not  depend  on  the  detailed implementation. Strategy PatternTemplate  Method  Pattern
  • 119. The  sorting  algorithm  consists  of:   1)  Generic  high  level  steps   Can  be  used  to  sort  items  of  any  type 2)  Detailed  operations/steps Operate  on  items  of  a  specific  type   Strategy Pattern Template  Method  Pattern
  • 120. The  TEMPLATE METHOD pattern  allows  a  generic  algorithm  to  manipulate  many  possible  detailed   implementations, But  Template  Method  partially violates the  DIP   because  it  uses  implementation  inheritance so  the  detailed  implementations   don't  depend  on  an  abstraction they  depend  on  the  generic  algorithm and  so  they  are  inextricably  bound  to  it   and  cannot  be  reused  by  other  generic  algorithms High-­‐level  modules  should  not  depend  on   low-­‐level  modules.   Both should  depend  on  abstractions. BubbleSorter’s doSort() method  satisfies the  DIP because  it  depends  on  abstract   methods  outOfOrder() and  swap() DoubleBubbleSorter and   IntegerBubbleSorter do  not  satisfy  the  DIP because  they  depend  on BubbleSorter,  which  is  NOT  an  abstraction since  it  contains  a  concrete  generic  algorithm DIP X Design  Smell:  Immobility Template  Method  Pattern
  • 121. The  Strategy pattern  fully  conforms to  the  DIP because  it  uses  interface  inheritance so  the  detailed  implementations  do  depend   on  an  abstraction(the  interface),   so  the  detailed  implementations  can  be  manipulated   by  (reused  for)  many  different  generic  algorithms Strategy  has  this  additional  benefit  over  Template  Method High-­‐level  modules  should  not  depend  on   low-­‐level  modules.   Both should  depend  on  abstractions. DIP Not  only  does  BubbleSorter satisfy the DIP, because its sort() method depends  on interface  SortHandler,  i.e.  an  abstraction but  IntegerSortHandler and   DoublSortHandler also  satisfy  the  DIP,  because  they  also   depend  on  the  SortHandler abstraction Strategy Pattern
  • 122. inherits  from (OO  inheritance) Original OCP The  original  version  of  the   OCP used  implementation inheritance While  the  contemporary  version  of  the   OCP mostly  uses  interface inheritance,   it  sometimes  does  use implementation inheritance realization Contemporary OCP generalization +
  • 123. In  many  ways,  the  OCP  is  at  the  heart  of  object-­‐oriented  design   Conformance  to  this  principle  is  what  yields  the  greatest  benefits  claimed   for  OO  technology:  flexibility,  reusability,  and  maintainability [it  is  not]  a  good  idea  to  apply  rampant  abstraction  to  every  part  of  the  application.   Rather,  it  requires  a  dedication  on  the  part  of  the  developers  to  apply  abstraction   only  to  those  parts  of  the  program  that  exhibit  frequent  change.   Resisting  premature  abstraction  is  as  important  as  abstraction  itself.
  • 124.
  • 126.
  • 127.
  • 128. References All  images  sourced  from  http://www.google.co.uk/advanced_image_search,  so  see  there  for  details  of   which  are    subject  to  copyright Object-­‐Oriented  Software  Construction  – by  Bertrand  Meyer;  Publication  Date:  3  April  1997  |  ISBN-­‐10:   0136291554  |  ISBN-­‐13:  978-­‐0136291558  |  Edition:  2 Flexible,  Reliable  Software:  Using  Patterns  and  Agile  Development  – by  Henrik B.  Christensen;   Publication  Date:  11  May  2010  |  ISBN-­‐10:  1420093622  |  ISBN-­‐13:  978-­‐1420093629 Design  Patterns  Explained:  A  New  Perspective  on  Object-­‐Oriented  Design;  by  Alan  Shalloway;   Publication  Date:  12  Oct  2004  |  ISBN-­‐10:  0321247140  |  ISBN-­‐13:  978-­‐0321247148  |  Edition:  2 Less  -­‐ The  Path  to  Better  Design;  by  Sandi  Metz  at  GoRuCo 2011  goruco_2011_-­‐_sandi_metz_-­‐_less_-­‐ _the_path_to_better_design_1280x720.mp4 Why  Extends  is  Evil  -­‐ Improve  your  code  by  replacing  concrete  base  classes  with  interfaces;  by   Allen  Holub;    http://www.javaworld.com/article/2073649/core-­‐java/why-­‐extends-­‐is-­‐evil.html