Design Patterns and Principles Part 2 Flashcards
universal principles of soft ware design
1: Encapsulate What Varies
1.1: Encapsulate on a method level
1.2: Encapsulate on a class level
2: Program to an Interface, not an implementation
3: Favor Composition Over Inheritance
● Identify the aspects of your application
that vary and separate them from what
stays the same.
● The main goal of this principle is to minimize
the effect caused by changes
●You can isolate the parts of the program
that vary in independent modules ,
protecting the code from adverse effects.
● With this, you spend less time getting the
program afloat”, more time for you to
implement features.
1: Encapsulate What Varies
●
Anticipate parts of your code that
might need to change in the future
●
If you knew that a part of your code
may change during the program’s
lifetime, you have to put it in a
separate method
●
This is to make sure that if ever that
part of a code changed, it is now
easier to isolate the problem without
ruining the entire code.
1.1: Encapsulate on a method level
●
Over time, you migh t want to add
more responsibilities to a method ,
which used to do a simple thing
●
Adding another me thod to help the
first method may help, but this may
blur the primary responsibility of the
containing class itself
●
Extracting the methods to another
class might make things much more
clear and simple.
1.2: Encapsulate on a class level
●
Depend on abstractions, not concrete
classes
●
Make sure that your design is flexible: the
code can be extended without breaking
existing code
●
This can allow classes to collaborate ,
adding further functionality and flexibility to
your code.
●
This is through the use of abstract classes
and polymorphism .
2: Program to an Interface, not an implementation
●
Inheritance is probably the most obvious and easy way of reusing code between classes.
3: Favor Composition Over Inheritance
● Unfortunately, inheritance comes with caveats that often become apparent only after your
program already has tons of classes and changing anything is pretty hard:
■
A subclass can’t reduce the interface of the superclass.
■
When overriding methods you need to make sure that the new behavior is
compatible with the base one.
■
Inheritance breaks encapsulation of the superclass
■
Subclasses are tightly coupled to superclasses
■
Trying to reuse code through inheritance can lead to creating parallel
inheritance hierarchies.
An alternative to inheritance is
composition.
If inheritance represents the “IS A”
relationship , composition represents
the “__” relationship
HAS A
You may also use a more relaxed
variant of composition , which is
called
aggregation