Cohesion

Cohesion

When diving into object-oriented programming (OOP), you’ve likely encountered the term "cohesion" at some point. And for good reason — it's all about how well the parts of a class or module relate to each other and collaborate to fulfill a single, clear purpose.

In today’s world of modern software development, cohesion is a big deal. It ensures your code isn’t a chaotic tangle of unrelated tasks and keeps your projects sane (and your teammates happy).

This article aims to underscore just how vital it is to write cohesive code, while nudging you, dear reader, to explore this topic further. Trust me, mastering cohesion might just delay the arrival of those premature gray hairs! ??


?? What is Cohesion?

In summary, cohesion measures how focused a class or module is on performing a specific task.

? When a class has a single, well-defined function and includes only the methods and fields necessary to accomplish that function, we call it highly cohesive.

? On the other hand, if a class handles multiple, unrelated responsibilities, it is said to have low cohesion.

Can you readily identify the purpose of the following class?

type
  TDataProcessor = class sealed
  public
    function ReadFile(const AFileName: string): Boolean;
    function AddValues(const AValue1, AValue2: Double): Double;
    function GenerateReport(const AFileName: string): Boolean;
    function ConvertToString(const AValue: Double): string;
    procedure SaveDataToDatabase(const AData: string);
  end;        

And this one?

type
    TCalculator = class sealed
    public
      function Add(const AValue1, AValue2 : Double) : Double;
      function Subtract(const AValue1, AValue2 : Double) : Double;
      function Multiply(const AValue1, AValue2 : Double) : Double;
      function Divide(const AValue1, AValue2 : Double) : Double;
    end;        

Which of these do you think is highly cohesive? If you chose the second one, you're correct! ??

??The TCalculator class is highly cohesive because all its methods are focused on a single responsibility: performing mathematical calculations.

The TDataProcessor, however, has low cohesion because it handles multiple, unrelated tasks such as reading files, adding values, generating reports, saving data to a database, and converting values to strings.


Note: Cohesion closely aligns with the Single Responsibility Principle (SRP), the "S" in the famous SOLID principles. By adhering to SRP, you can design robust classes with a singular reason to change. Want to dig deeper? Check this out for more details!


So, what do our systems gain from this? Let’s take a look at some benefits.


??Readability

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

This quote by Martin Fowler emphasizes a key principle of software development: writing code that not only works for the machine but is also easy for humans to understand.

Well-organized, well-written, and cohesive code significantly improves its readability, making it easier for the programmer who wrote it and for anyone who needs to work with it in the future.


??Easier to Maintain

Cohesive code, with a clear and focused purpose, simplifies long-term maintenance. When code is neatly organized into well-defined classes and functions, it becomes easier to fix bugs, add new features, or refactor without unintentionally introducing errors.

A highly cohesive class or method will have fewer interdependencies, making modifications straightforward and less risky.


????Improved Collaboration

Clear and well-structured code fosters better collaboration among team members. Developers can work together seamlessly, knowing that their changes won’t inadvertently affect other parts of the system.

When code is cohesive, it ensures that each module or class serves a specific, well-defined function, avoiding unnecessary complexity and reducing the risk of conflicting changes. This trust in the system's structure leads to more efficient teamwork.


Gold Tips

  • Define Clear Responsibilities: Ensure each class is responsible for a single, clearly defined task.

Note: Use techniques like Class-Responsibility-Collaboration (CRC) cards to brainstorm the role of each class.

  • Adhere to the SRP: Each class should handle one aspect of the system’s functionality.
  • Decompose Large Classes: Split large, multi-purpose classes into smaller, more focused ones.
  • Encapsulate Related Behavior: Ensure that a class’s methods and attributes work together to fulfill its purpose
  • Refactor Regularly: As a system evolves, regularly refactor classes to maintain cohesion.


Conclusion

Cohesion is a cornerstone of good OOP. By ensuring that each class has a clear, focused responsibility, developers can create code that is easier to read, maintain, and extend.

By focusing on this critical aspect of design, you can build scalable and sustainable software systems.

#Delphi #DelphiDevelopers #DelphiTips #DelphiCode #OOP #Cohesion #SRP #CleanCode #Programming

要查看或添加评论,请登录

Leandro Siqueira的更多文章

  • Transforming Models for Real-World Impact

    Transforming Models for Real-World Impact

    As an AI Specialist and Technical Trainer, I'm excited to share techniques that empower tech learners to build better…

  • Unlocking Development Challenges with the '5 Whys' Framework

    Unlocking Development Challenges with the '5 Whys' Framework

    Every developer, whether working on AI, web applications, or enterprise systems, faces roadblocks. But before…

    2 条评论
  • From Chaotic If-Else to Elegant, Maintainable Class Structure

    From Chaotic If-Else to Elegant, Maintainable Class Structure

    In the world of software development, there’s one concept that often differentiates novice developers from seasoned…

  • The Open/Closed Principle

    The Open/Closed Principle

    ?? ?????? ????????/???????????? ?????????????????? (??????) ???? ?????? ???? ?????? ????????????????????????…

  • The Single Responsibility Principle

    The Single Responsibility Principle

    ??C?????? ?????????????? ?????? ?????????????????????????????? ?????? ?????????????? ?????? ?????? ?????????????? ????…

  • Keep Calm and Code In Delphi #4

    Keep Calm and Code In Delphi #4

    ??Enumerated Types Enumerated types (or simply "enums") allow you to create ordered sets of predefined values and are…

  • Keep Calm and Code in Delphi - #3

    Keep Calm and Code in Delphi - #3

    ?? Linked Lists Linked Lists are one of the most powerful and flexible data structures, widely used to implement…

    1 条评论

社区洞察

其他会员也浏览了