OO Principles - Rest of the Gang
I finally had time to go over the other Object Oriented Principles. Lack of time (and some laziness) is preventing me from posting an example and discussing each one of them in detail. So I am going to stop with the definitions and add some comments. Before I get into the principles one line that particuary caught my attention in Martins book was
“An Axis of change is an axis of change only if the changes occur”.
Martin warns us against applying any of the principles if the symptom does not exist. One thing that might help us define these symptoms early are Unit tests. Here are the principles
- The Open/Closed Principle: A Software Entity (mostly class) should be open for extension but closed for modification.
My favorite principle! Closed to Modification indicates that we would not change the source code and thus not cause the application depending on the code(in a dll in .NET) to be recompiled. Using
abstraction (base class) we would allow the class to be extended by defining new classes(derived
from old class) that would define new behavior! - Liskov Substitution Principle: Subtypes must be substitutable for their base types.
The most important thing to remember is not to blindly follow the “IS-A” rule of inheritance. As martin explains, A Square is a Rectangle might look like it is a perfect match for the “IS-A” relationship, but Passing a Square(height = 5, width = 5) to a method that accepts Rectangle and changing width(to 6 for example) would result in a Square with unequal sides breaking the assumption that Squares have same height and width leading to unexpected errors. - Dependency Inversion Principle: High Level modules should not depend on low level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend on abstractions.
This principle pretty much violates what I was doing fresh out of school J . In a way as martin describes, violating this principle would lead your program to be more rigid and also make your program look like traditional procedural programming and I am sure we don’t want that to happen for a lot of reasons! - Interface Aggregation Principle: Clients should not be forced to depend on methods they do not use.
Without unit tests, with a big development team and new features, violating this principle can lead to a lot of problems. Most of the time you land up with “dead code” in your project that is not used by the classes containing it and exists for confusing developers!
The most preferred approach of implementing this principle in the case where there is a Fat interface is to split
it up to small interfaces and have the client implement all the small interfaces.
HTH
Hari


Comments