Monday, September 20, 2010

Loosely coupled and highly cohesive

  1. Coupling
    1. among classes
    2. among subsystems, modules
    3. related classes knowing the internal details of each other
    4. when one is changed, other has to be changed
    5. makes the system difficult to understand
    6. no possibility of reuse of the entwined code
  2. Cohesion
    1. inside the class, among the class attributes and behavior
    2. well defined roles for the classes within the system
    3. the data is closely related with the functions which the class is providing
  3.  

  4. Law of Demeter (more specific case of "low coupling", LoD)
    1. motto is "only talk to your immediate friends"
    2. each unit should have only limited knowledge about other units "closely" related to the current unit (method/function "f")
    3. in context of OOD, closely related
      1. are the functions of the class in which unit (function "f") exists
      2. other argument classes of unit (function "f")
      3. functions of immediate part classes (computed and stored) of class of unit (function "f")
        1. computed classes are the classes that are the return type of functions of this class
        2. stored classes are the classes of the data members of this class

  5. Tell (what to do, command) don't ask (putting class responsibilities in right place)
    1. tell objects what you want them to do
    2. do not ask questions about their state and then make a decision
    3. why not ask ? the decision (based on some state) has to made by the owner of that state
    4. for a non owner to take decision based on some other class state violates encapsulation, and increases coupling
    5. design the classes based on their responsibilities, specify the commands that the classes may execute
    6. if the responsibility of the class is rightly designed, it leads to loose coupling among classes
  6. Say it once and only once (don't repeat yourself ,DRY)
    1. avoiding the duplication of information (code) in a program
    2. "the rule of three" devised by Martin Fowler states that of a piece of code is copied more than once (3 or more copies) then it need to be abstracted out.
    3. if different pieces of code are performing the same function then, abstract out the parts that varies, and combine the part that is same for all (thus not repeating).

     

References
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/general-formulation.html
http://pragprog.com/articles/tell-dont-ask
http://en.wikipedia.org/wiki/Abstraction_principle_(programming)

No comments: