Difference between revisions of "OO Best Practice"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 41: Line 41:
 
== Encapsulation ==
 
== Encapsulation ==
  
 
+
* Encapsulation helps to make the distinction between an object's contract and implementation.
 
+
* Encapsulation is achieved through information hiding.
 +
* At the class level, The implementation fields should be made private and the contract would be exposed through public methods.
 +
* At the package level - classes that belong together should be grouped into relevant packages and inter-package accessibility can be controlled.
  
 
[[Category:OCPJP]]
 
[[Category:OCPJP]]

Revision as of 21:45, 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

  • Encapsulation helps to make the distinction between an object's contract and implementation.
  • Encapsulation is achieved through information hiding.
  • At the class level, The implementation fields should be made private and the contract would be exposed through public methods.
  • At the package level - classes that belong together should be grouped into relevant packages and inter-package accessibility can be controlled.