You change something in a class. You change something unrelated in the same class
TL:DR; Classes should have just one responsibility and one reason to change.
Problems
Code Duplication
Low Cohesion
Single Responsibility Principle violation
Solutions
- Extract class
Context
We create classes to fulfill responsibilities.
If an object does too much, it might change in different directions.
Sample Code
Wrong
class Webpage {
renderHTML(): {
renderDocType();
renderTitle();
renderRssHeader();
renderRssTitle();
renderRssDescription();
// ...
}
//HTML render can change
renderRssDescription() {
// ...
}
renderRssTitle() {
// ...
}
renderRssPubDate() {
// ...
}
//RSS Format might change
}
Right
class Webpage {
renderHTML() {
this.renderDocType();
this.renderTitle();
(new RSSFeed()).render();
this.renderRssTitle();
this.renderRssDescription();
// ...
}
//HTML render can change
}
class RSSFeed {
render() {
this.renderDescription();
this.renderTitle();
this.renderPubDate();
//...
}
//RSS Format might change
//Might have unitary tests
//etc
}
Detection
[X] Semi Automatic
We can automatically detect large classes or track changes.
Tags
- Coupling
Conclusion
Classes must follow the Single Responsibility Principle and have just one reason to change.
If they evolve in different ways, they are doing too much.
Relations
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Code Smell 90 - Implementative Callback Events
Maxi Contieri ・ Oct 7 '21
More Info
A design that doesn’t take change into account risks major redesign in the future.
Erich Gamma
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (0)