Search code examples
javaooploose-couplingcohesion

optimization of high cohesion and loose coupling


I was questioned in a technical interview about cohesion and coupling of a project. I extensively explained their definitions, although I did not answer the second part of the question properly, as he said.

"How could we achieve a highly cohesive and loosely coupled design in a project simultaneously and please explain how should this approach be implemented in a monolithic project ?"

I answered that these two objectives are contradictory, so we need to find out the best bet for each project or module, but I could not provide a comprehensive answer.

I would appreciate if anyone helps me out.


Solution

  • I want to begin answering by saying that it is exactly opposite of what you said as “the two definition are contradictory”. I'm going describe by bringing a quote from John W. Satzinger System Analysis and Design in a Changing World, Key Facts book

    Low coupling often correlates with high cohesion, and vice versa


    By saying in a Monolithic they were signaling you to ask about the SOLID principals that if you apply them, result in a High Cohesion and loose coupling project.

    Here is the definitions :

    1.Single-responsibility principle (SRP)

    Definition: There should be never more than one reason for a class to change.

    Benefits:

    • stronger cohesion in the class
    • looser coupling between dependency classes,
    • better readability
    • code with lower complexity
    • Code easier to understand and maintain.

    2. Open-closed principle (OCP)

    Definition: Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

    Benefits:

    • loose coupling,
    • improving readability
    • reducing the risk of breaking existing functionality
    • Code maintainable and reusable.
    • Code more robust.

    3. Liskov substitution principle (LSP)

    Definition: Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

    Benefits:

    • loose coupling
    • Code more reusable.
    • Class hierarchies easy to understand.

    4. Interface segregation principle (ISP)

    Definition: many client-specific interfaces are better than one general-purpose interface

    Benefits:

    • Decoupled system.
    • Code easy to refactor.

    5. Dependency Inversion Principle (DIP)

    Definition: High-level modules should not depend on low level modules, rather both should depend on abstraction. Abstraction should not depend on details; rather detail should depend on abstraction.

    Benefits:

    • high cohesion.
    • Reduce the coupling.
    • Code more reusable.

    More Information


    Books

    • Steve McConnell's Code Complete
    • Uncle Bob's Clean Code