{"id":142,"date":"2025-01-20T21:14:14","date_gmt":"2025-01-20T21:14:14","guid":{"rendered":"https:\/\/www.fabricioruch.ch\/?p=142"},"modified":"2025-02-17T20:37:52","modified_gmt":"2025-02-17T20:37:52","slug":"high-cohesion-vs-low-cohesion-in-software-design","status":"publish","type":"post","link":"https:\/\/www.fabricioruch.ch\/?p=142","title":{"rendered":"High Cohesion vs. Low Cohesion in Software Design"},"content":{"rendered":"\n<p>When designing software systems, the concept of <strong>cohesion<\/strong> plays a crucial role in determining the quality and maintainability of your code. Cohesion refers to how closely related the responsibilities of a single module or class are. Understanding the difference between <strong>high cohesion<\/strong> and <strong>low cohesion<\/strong> is essential for writing clean, robust, and scalable code.<\/p>\n\n\n\n<p>In this blog post, we\u2019ll explore what cohesion means, compare high and low cohesion, and provide practical examples to illustrate these principles.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What is Cohesion?<\/h2>\n\n\n\n<p>Cohesion measures how well the parts of a module or class fit together to achieve a single purpose. It reflects the degree to which the responsibilities of a class or module are focused and aligned.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Types of Cohesion:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>High Cohesion<\/strong>:\n<ul class=\"wp-block-list\">\n<li>A module or class has a clear, well-defined responsibility.<\/li>\n\n\n\n<li>All methods and properties work toward a single, unified goal.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Low Cohesion<\/strong>:\n<ul class=\"wp-block-list\">\n<li>A module or class is responsible for unrelated tasks.<\/li>\n\n\n\n<li>The code becomes harder to understand, maintain, and test.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">High Cohesion<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Characteristics of High Cohesion:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Each module or class focuses on a single responsibility.<\/li>\n\n\n\n<li>Follows the <strong>Single Responsibility Principle (SRP)<\/strong> from SOLID design principles.<\/li>\n\n\n\n<li>Promotes maintainability, testability, and readability.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example of High Cohesion:<\/h3>\n\n\n\n<p>Here\u2019s a <code>UserService<\/code> class designed with high cohesion:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class UserService\n{\n    private readonly IUserRepository _userRepository;\n    private readonly IEmailService _emailService;\n\n    public UserService(IUserRepository userRepository, IEmailService emailService)\n    {\n        _userRepository = userRepository;\n        _emailService = emailService;\n    }\n\n    public User GetUserById(int id)\n    {\n        return _userRepository.GetById(id);\n    }\n\n    public void RegisterUser(User user)\n    {\n        _userRepository.Add(user);\n        _emailService.SendWelcomeEmail(user.Email);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why It\u2019s High Cohesion:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>UserService<\/code> class handles user-related functionality only.<\/li>\n\n\n\n<li>Responsibilities like database access and email sending are delegated to other classes, adhering to SRP.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits of High Cohesion:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Easier Maintenance<\/strong>: Changes are localized to specific classes.<\/li>\n\n\n\n<li><strong>Better Testability<\/strong>: Focused responsibilities make it easier to write unit tests.<\/li>\n\n\n\n<li><strong>Improved Reusability<\/strong>: Components can be reused in other parts of the system.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Low Cohesion<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Characteristics of Low Cohesion:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A single module or class takes on multiple unrelated responsibilities.<\/li>\n\n\n\n<li>Violates the Single Responsibility Principle.<\/li>\n\n\n\n<li>Leads to tightly coupled and harder-to-maintain code.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example of Low Cohesion:<\/h3>\n\n\n\n<p>Here\u2019s an example of a <code>UserManager<\/code> class with low cohesion:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class UserManager\n{\n    public User GetUserById(int id)\n    {\n        \/\/ Logic to fetch user from database\n        Console.WriteLine(\"Fetching user from database\");\n        return new User { Id = id, Name = \"John Doe\" };\n    }\n\n    public void SendEmail(string email, string message)\n    {\n        \/\/ Logic to send an email\n        Console.WriteLine($\"Sending email to {email}: {message}\");\n    }\n\n    public void Log(string message)\n    {\n        \/\/ Logic to log a message\n        Console.WriteLine($\"Log: {message}\");\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why It\u2019s Low Cohesion:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>UserManager<\/code> class handles database operations, email sending, and logging, which are unrelated responsibilities.<\/li>\n\n\n\n<li>Violates SRP by mixing different concerns.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Drawbacks of Low Cohesion:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Difficult to Maintain<\/strong>: A change in one responsibility may unintentionally affect others.<\/li>\n\n\n\n<li><strong>Harder to Test<\/strong>: Writing focused unit tests is challenging when a class does too much.<\/li>\n\n\n\n<li><strong>Poor Reusability<\/strong>: The class is tightly coupled and cannot be easily reused elsewhere.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Key Differences Between High and Low Cohesion<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><strong>Aspect<\/strong><\/th><th><strong>High Cohesion<\/strong><\/th><th><strong>Low Cohesion<\/strong><\/th><\/tr><\/thead><tbody><tr><td><strong>Focus<\/strong><\/td><td>Single, well-defined responsibility<\/td><td>Multiple, unrelated responsibilities<\/td><\/tr><tr><td><strong>Maintainability<\/strong><\/td><td>Easy to maintain and extend<\/td><td>Difficult to maintain and extend<\/td><\/tr><tr><td><strong>Testability<\/strong><\/td><td>Easy to test in isolation<\/td><td>Hard to test due to mixed concerns<\/td><\/tr><tr><td><strong>Reusability<\/strong><\/td><td>High reusability of focused components<\/td><td>Low reusability due to tight coupling<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How to Achieve High Cohesion<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Follow the Single Responsibility Principle (SRP):<\/strong>\n<ul class=\"wp-block-list\">\n<li>Ensure each class or module focuses on one responsibility.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Use Abstraction:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Delegate unrelated responsibilities to different interfaces or classes.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Refactor Often:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Regularly review your code to identify and separate mixed responsibilities.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Leverage Design Patterns:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Patterns like <strong>Factory<\/strong>, <strong>Strategy<\/strong>, and <strong>Observer<\/strong> can help separate concerns.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Real-World Example: Refactoring to High Cohesion<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Before Refactoring (Low Cohesion):<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class OrderManager\n{\n    public void PlaceOrder(Order order)\n    {\n        Console.WriteLine(\"Saving order to database\");\n        Console.WriteLine(\"Sending order confirmation email\");\n        Console.WriteLine(\"Logging order details\");\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">After Refactoring (High Cohesion):<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class OrderService\n{\n    private readonly IOrderRepository _orderRepository;\n    private readonly IEmailService _emailService;\n    private readonly ILogger _logger;\n\n    public OrderService(IOrderRepository orderRepository, IEmailService emailService, ILogger logger)\n    {\n        _orderRepository = orderRepository;\n        _emailService = emailService;\n        _logger = logger;\n    }\n\n    public void PlaceOrder(Order order)\n    {\n        _orderRepository.Save(order);\n        _emailService.SendOrderConfirmation(order.Email);\n        _logger.Log(\"Order placed successfully\");\n    }\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Cohesion is a fundamental principle of clean code and software design. High cohesion results in maintainable, testable, and reusable code, while low cohesion can lead to tightly coupled, hard-to-manage systems. By following best practices like SRP, abstraction, and refactoring, you can ensure your codebase remains flexible and easy to work with.<\/p>\n\n\n\n<p>Keep these principles in mind as you design and refactor your applications, and you\u2019ll build systems that stand the test of time.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>References and Further Reading<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">English<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>&#8222;Coupling and Cohesion &#8211; Software Engineering&#8220;<\/strong><br>This article from GeeksforGeeks provides a comprehensive overview of coupling and cohesion, discussing their significance in software engineering and how they impact system design.<br><a href=\"https:\/\/www.geeksforgeeks.org\/software-engineering-coupling-and-cohesion\/\">https:\/\/www.geeksforgeeks.org\/software-engineering-coupling-and-cohesion\/<\/a><\/li>\n\n\n\n<li><strong>&#8222;High Cohesion and Low Coupling: A Foundation for Robust Software Design&#8220;<\/strong><br>Published on Medium, this article delves into the principles of high cohesion and low coupling, offering insights into creating well-structured and maintainable applications.<br><a href=\"https:\/\/medium.com\/@Masoncoding\/high-cohesion-and-low-coupling-a-foundation-for-robust-software-design-f12eefc3b53f\">https:\/\/medium.com\/@Masoncoding\/high-cohesion-and-low-coupling-a-foundation-for-robust-software-design-f12eefc3b53f<\/a><\/li>\n\n\n\n<li><strong>&#8222;Low Coupling, High Cohesion&#8220;<\/strong><br>This Medium article discusses the benefits of designing software with low coupling and high cohesion, providing practical examples and insights.<br><a href=\"https:\/\/medium.com\/clarityhub\/low-coupling-high-cohesion-3610e35ac4a6\">https:\/\/medium.com\/clarityhub\/low-coupling-high-cohesion-3610e35ac4a6<\/a><\/li>\n\n\n\n<li><strong>&#8222;High Cohesion, Low Coupling&#8220;<\/strong><br>An article by Seven Hills Technology that explores the concepts of high cohesion and low coupling, illustrating their application in software development.<br><a href=\"https:\/\/www.sevenhillstechnology.com\/blog\/high-cohesion-low-coupling\">https:\/\/www.sevenhillstechnology.com\/blog\/high-cohesion-low-coupling<\/a><\/li>\n\n\n\n<li><strong>&#8222;Impact of Coupling and Cohesion in Object-Oriented Technology&#8220;<\/strong><br>This research paper examines how coupling and cohesion affect object-oriented design, providing empirical data and analysis.<br><a href=\"https:\/\/www.researchgate.net\/publication\/264889762_Impact_of_Coupling_and_Cohesion_in_Object-Oriented_Technology\">https:\/\/www.researchgate.net\/publication\/264889762_Impact_of_Coupling_and_Cohesion_in_Object-Oriented_Technology<\/a><\/li>\n\n\n\n<li><strong>&#8222;GRASP (Object-Oriented Design)&#8220;<\/strong><br>The Wikipedia entry on GRASP (General Responsibility Assignment Software Patterns) offers insights into various design principles, including low coupling and high cohesion.<br><a href=\"https:\/\/en.wikipedia.org\/wiki\/GRASP_(object-oriented_design)\">https:\/\/en.wikipedia.org\/wiki\/GRASP_(object-oriented_design)<\/a><\/li>\n\n\n\n<li><strong>&#8222;Cohesion (Computer Science)&#8220;<\/strong><br>This Wikipedia article provides an in-depth look at cohesion in computer science, discussing its various types and importance in software design.<br><a href=\"https:\/\/en.wikipedia.org\/wiki\/Cohesion_(computer_science)\">https:\/\/en.wikipedia.org\/wiki\/Cohesion_(computer_science)<\/a><\/li>\n\n\n\n<li><strong>&#8222;Coupling (Computer Programming)&#8220;<\/strong><br>The Wikipedia page on coupling offers a detailed exploration of the concept, including its types and implications in software engineering.<br><a href=\"https:\/\/en.wikipedia.org\/wiki\/Coupling_(computer_programming)\">https:\/\/en.wikipedia.org\/wiki\/Coupling_(computer_programming)<\/a><\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Deutsch<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>&#8222;Koh\u00e4sion und Kopplung: Informatik &amp; Beispiele&#8220;<\/strong><br>Dieser Artikel von StudySmarter bietet eine umfassende Einf\u00fchrung in die Konzepte der Koh\u00e4sion und Kopplung, erl\u00e4utert deren Bedeutung in der Softwareentwicklung und stellt anschauliche Beispiele zur Verf\u00fcgung.<br><a href=\"https:\/\/www.studysmarter.de\/ausbildung\/ausbildung-in-it\/fachinformatiker-anwendungsentwicklung\/kohaesion-und-kopplung\/\">https:\/\/www.studysmarter.de\/ausbildung\/ausbildung-in-it\/fachinformatiker-anwendungsentwicklung\/kohaesion-und-kopplung\/<\/a><\/li>\n\n\n\n<li><strong>&#8222;Lose Kopplung&#8220;<\/strong><br>Der Wikipedia-Artikel erkl\u00e4rt den Begriff der losen Kopplung in der Informatik und diskutiert deren Vorteile f\u00fcr die Wartbarkeit und Flexibilit\u00e4t von Softwaresystemen.<br><a href=\"https:\/\/de.wikipedia.org\/wiki\/Lose_Kopplung\">https:\/\/de.wikipedia.org\/wiki\/Lose_Kopplung<\/a><\/li>\n\n\n\n<li><strong>&#8222;Koh\u00e4sion (Informatik)&#8220;<\/strong><br>In diesem Wikipedia-Artikel wird das Konzept der Koh\u00e4sion im Kontext der objektorientierten Programmierung detailliert beschrieben, einschlie\u00dflich verschiedener Arten von Koh\u00e4sion und deren Einfluss auf die Softwarequalit\u00e4t.<br><a href=\"https:\/\/de.wikipedia.org\/wiki\/Koh%C3%A4sion_(Informatik)\">https:\/\/de.wikipedia.org\/wiki\/Koh%C3%A4sion_(Informatik)<\/a><\/li>\n\n\n\n<li><strong>&#8222;Kopplung und Koh\u00e4sion &#8211; fundamentale oder abgeleitete Konzepte?&#8220;<\/strong><br>In diesem Blogbeitrag werden die Grundlagen und die Bedeutung von Kopplung und Koh\u00e4sion in der Softwaretechnik diskutiert, wobei der Fokus auf deren Einfluss auf zuk\u00fcnftige \u00c4nderungen und die Wartbarkeit von Software liegt.<br><a href=\"https:\/\/prinzipien-der-softwaretechnik.blogspot.com\/2013\/02\/kopplung-und-kohasion-fundamentale-oder.html\">https:\/\/prinzipien-der-softwaretechnik.blogspot.com\/2013\/02\/kopplung-und-kohasion-fundamentale-oder.html<\/a><\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>When designing software systems, the concept of cohesion plays a crucial role in determining the quality and maintainability of your code. Cohesion refers to how closely related the responsibilities of a single module or class are. Understanding the difference between&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5,12,21,27,8,25],"tags":[],"class_list":["post-142","post","type-post","status-publish","format-standard","hentry","category-csharp","category-computer-science","category-learning","category-programming-principles","category-software-architecture","category-software-engineering"],"_links":{"self":[{"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=\/wp\/v2\/posts\/142","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=142"}],"version-history":[{"count":4,"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=\/wp\/v2\/posts\/142\/revisions"}],"predecessor-version":[{"id":171,"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=\/wp\/v2\/posts\/142\/revisions\/171"}],"wp:attachment":[{"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=142"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=142"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.fabricioruch.ch\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=142"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}