OO Best Practice
From Suhrid.net Wiki
Jump to navigationJump to searchContents
Intro
- Exam focuses on recognizing tight encapsulation, loose coupling and high cohesion.
Coupling
- Coupling is the degree to which one class knows about the other class.
- Ideally a class should know about another class only through what has been exposed through its interface/API.
- If two classes know internal details about each other - they are said to be tightly coupled. This would mean that they cannot be modified independently.
- For e.g. if we use the generic type List in our public API, instead of ArrayList we can always change the internal implementation later to say, a LinkedList for performance reasons and clients of our API would need not change their code.
Cohesion
- Cohesion is all about how a single class is designed.
- Cohesion is used to indicate the degree to which a class has a single well-focused purpose.
- For e.g. in the below class has low cohesion, since it does a variety of things. The code should be split up to ensure that each class performs one functions and so is reusable:
class TaxReport {
void connectToDB();
void generatePDF();
void compute();
}
//Split for high cohesion:
class TaxReport {
void compute();
}
class PDFUtil {
void generatePDF();
}
class DBUtil {
void connectToDB();
}