Cohesion (High vs Low) in Software Engineering

beginner
21 min

Cohesion (High vs Low) in Software Engineering

Welcome to CodeYourCraft's lesson on Cohesion in Software Engineering! šŸŽÆ

This lesson is designed to help you understand the concept of Cohesion, a crucial aspect of software design that ensures the quality and maintainability of your code. Let's get started!

What is Cohesion?

Cohesion in software engineering refers to how closely the components of a module are related to each other and to the module's goal. High cohesion means that a module performs a single, well-defined task, while low cohesion indicates that a module does multiple unrelated things.

Importance of Cohesion

Cohesion plays a vital role in software development for several reasons:

  1. Ease of Understanding: High cohesion makes it easier for developers to understand the purpose of a module, as it performs a single, well-defined task.

  2. Maintainability: High cohesion makes it easier to maintain and update code, as changes are confined to a single module.

  3. Reusability: High cohesion makes it easier to reuse modules, as they perform a specific task and can be easily integrated into other systems.

  4. Error Detection: High cohesion makes it easier to identify and isolate errors, as the cause of a problem is more likely to be within a single module.

High Cohesion Examples

Let's consider an example of a function that calculates the area of a rectangle. This function only performs one task, making it a good example of high cohesion.

python
def calculate_rectangle_area(length, width): return length * width

šŸ“ Note: This function is specifically designed to calculate the area of a rectangle. It doesn't perform any other tasks, making it highly cohesive.

Low Cohesion Examples

On the other hand, a function that calculates the area of various shapes (rectangle, circle, triangle) would exhibit low cohesion, as it performs multiple, unrelated tasks.

python
def calculate_area(shape, parameters): if shape == "rectangle": length, width = parameters return length * width elif shape == "circle": radius = parameters return 3.14 * radius ** 2 # Add more shapes here

šŸ’” Pro Tip: Low cohesion can make your code harder to understand, maintain, and reuse. It's generally better to break your code into smaller, more focused modules.

Quiz Time! šŸ‘©ā€šŸ’»

Quick Quiz
Question 1 of 1

What is Cohesion in Software Engineering?

That's it for today! In our next lesson, we'll dive deeper into the concept of Coupling, another important aspect of software design. Stay tuned! šŸ‘‹

Remember, the goal is to create well-designed, easy-to-maintain, and reusable code. High cohesion is a key step in achieving that goal. Happy coding! šŸ’»šŸ“š