Explain that question "What is cohesion in OOP?" Use TS in your explanations.
- User
Explain that question "What is cohesion in OOP?" Use TS in your explanations.
- Assistant
Explain that question "What is cohesion in OOP?" Use TS in your explanations.
Cohesion is a fundamental concept in object-oriented programming (OOP) that refers to how closely related and focused the responsibilities of a single module or class are. High cohesion within a class or module means that its responsibilities are closely related and focused on a single task or purpose. This leads to more maintainable, understandable, and reusable code.
In contrast, low cohesion indicates that a class or module has multiple responsibilities that are not closely related, making the code harder to maintain and understand.
Using TypeScript, we can illustrate both high and low cohesion with examples.
Let's consider a scenario where we have a User class responsible for managing user-related data and behaviors. To achieve high cohesion, this class should only handle user-specific functionalities.
// User.ts
class User {
private name: string;
private email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
// Single Responsibility: Manage user data
getName(): string {
return this.name;
}
getEmail(): string {
return this.email;
}
// Single Responsibility: Manage user behavior
sendEmail(message: string): void {
// Logic to send email
console.log(`Sending email to ${this.email}: ${message}`);
}
}
// Usage
const user = new User('Alice', 'alice@example.com');
console.log(user.getName()); // Alice
user.sendEmail('Welcome to our platform!');
Explanation:
User class is solely responsible for managing user data (name and email) and related behaviors (e.g., sending an email).Now, let's look at a UserManager class with low cohesion, where it handles multiple unrelated responsibilities.
// UserManager.ts
class UserManager {
private users: User[] = [];
addUser(user: User): void {
this.users.push(user);
}
removeUser(user: User): void {
this.users = this.users.filter(u => u !== user);
}
// Unrelated Responsibility: Logging
logUserActivity(activity: string): void {
console.log(`User activity: ${activity}`);
}
// Unrelated Responsibility: Calculations
calculateUserStatistics(): number {
return this.users.length;
}
}
// Usage
const userManager = new UserManager();
const user = new User('Bob', 'bob@example.com');
userManager.addUser(user);
userManager.logUserActivity('Added a new user.');
console.log(userManager.calculateUserStatistics()); // 1
Explanation:
UserManager class handles user management (addUser, removeUser) and unrelated responsibilities such as logging user activity (logUserActivity) and calculating statistics (calculateUserStatistics).To improve cohesion, we can separate the responsibilities into different classes.
// User.ts
class User {
constructor(public name: string, public email: string) {}
}
// UserManager.ts
class UserManager {
private users: User[] = [];
addUser(user: User): void {
this.users.push(user);
}
removeUser(user: User): void {
this.users = this.users.filter(u => u !== user);
}
getUserCount(): number {
return this.users.length;
}
}
// Logger.ts
class Logger {
log(message: string): void {
console.log(message);
}
}
// Usage
const userManager = new UserManager();
const logger = new Logger();
const user = new User('Charlie', 'charlie@example.com');
userManager.addUser(user);
logger.log(`Added user: ${user.name}`);
console.log(`Total users: ${userManager.getUserCount()}`); // 1
Explanation:
User Class: Manages user data.UserManager Class: Manages user-related operations like adding or removing users and retrieving user counts.Logger Class: Handles logging activities.By separating these concerns:
Cohesion is a measure of how closely related the functionalities within a class or module are. Striving for high cohesion by ensuring that each class or module has a single, well-defined responsibility leads to cleaner, more maintainable, and robust code. Using TypeScript, as shown in the examples, helps enforce these principles through its strong typing and class-based structure.
Not yet included in a published release.