Solution: Software Layers
Reduce software couplingMinimize the consequences of changeFocused Unit Tests to verify changeExample of Code Refactoring
class Engine{
string manufacturer;int horsepower;
void Start(){…};void Stop(){…};
}
class Wheel{string manufacturer;float tirePressure;
void Turn(){…};}
Object composition introduces dependencies
Write your applications so that the dependencies of one type on another are eliminated or minimized.
Interfaces
interface IEngine{
void Start();void Stop();
}
interface IWheel{
void Turn();}
Interfaces describe behavior, not implementation
Rewritten Engine, Wheel Classes
class Engine : IEngine{ string manufacturer;
int horsepower;
void Start () {…}void Stop() {…}
}
class Wheel : IWheel{
string manufacturerfloat tirePressure;
void Turn();}
Interfaces Hide Implementation
class Diesel: IEngine{ string manufacturer;
int horsepower;
void Start () {…}void Stop() {…}
}
class WankelEngine : IEngine{
string manufacturer;int rotationSpeed;
void Start () {…}void Stop() {…}
}
Coupling
Preserve Essential CouplingEssential Semantics
Remove Inessential CouplingProgramming Artifacts
Electrical Analogy
Wall socket interface removes the inessential coupling due to the physical shape of plugs and appliances
An interface cannot remove the essential behavioral coupling of voltage and amperage of standard current
Complexity vs. Flexibility
Interfaces add a level of indirectionPut interfaces along application fault linesHard to refactor out of a bad design
Interfaces vs. Inheritance
Favor interface over object compositionInterface Composition vs. Inheritance?
class RacingCar : HighPerformanceCar : Auto
Static DefinitionNeed to Understand Base Class Behavior
"Inheritance Breaks Encapsulation"
class HighPerformanceCar{
virtual void Start(){
TurnIgnition();Press GasPedal();
}…}
class RacingCar : HighPerformanceCar
{…}
Interfaces
Avoid Inheriting ImplementationRestrict Inessential CouplingMake Interfaces Easy to Modify
Design Patterns
Minimize Dependencies in Implementation Use Design PatternsElectrical Analogy
Design to work with 110 or 220 volts?Use Transformer PatternFlexibility even with Essential Coupling
Top Related