Difference between revisions of "OO Best Practice"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 14: Line 14:
 
* Cohesion is all about how a ''single'' class is designed.
 
* 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.
 
* 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.
+
* 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:
  
 +
<syntaxhighlight lang="java5">
 
class TaxReport {
 
class TaxReport {
 
   void connectToDB();
 
   void connectToDB();
Line 22: Line 23:
 
}
 
}
  
* The code should be split up to ensure that each class performs one functions and so is reusable:
+
//Split for high cohesion:
  
 
class TaxReport {
 
class TaxReport {
Line 35: Line 36:
 
   void connectToDB();
 
   void connectToDB();
 
}
 
}
 +
 +
</syntaxhighlight>
 +
 +
== Encapsulation ==
 +
 +
  
  
 
[[Category:OCPJP]]
 
[[Category:OCPJP]]

Revision as of 21:38, 21 August 2011

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();
}

Encapsulation