![cover-img](https://project-assets.showwcase.com/1420x/16381/1682387405658-becca-tapert-F0ZiHWliGGM-unsplash.jpg?type=webp)
Code Smell 64 - Inappropriate Intimacy
25 April, 2023
3
3
0
Contributors
TL;DR: Don't get too intimate
Two classes entangled in love.
Problems
- Coupling
- Bad Responsibilities Assignments
- Bad Cohesion
- Class Interfaces too Public
- Maintainability
- Extensibility
Solutions
- Refactor
- Merge
- Replace Hierarchy With Delegation.
Sample Code
Wrong
class Candidate {
void printJobAddress(Job job) {
System.out.println("This is your position address");
System.out.println(job.address().street());
System.out.println(job.address().city());
System.out.println(job.address().zipCode());
if (job.address().country() == job.country()) {
System.out.println("It is a local job");
}
}
Right
final class Address {
void print() {
System.out.println(this.street);
System.out.println(this.city);
System.out.println(this.zipCode);
}
bool isInCounty(Country country) {
return this.country == country;
}
class Job {
void printAddress() {
System.out.println("This is your position address");
this.address().print());
if (this.address().isInCountry(this.country()) {
System.out.println("It is a local job");
}
}
}
class Candidate {
void printJobAddress(Job job) {
job.printAddress();
}
}
Detection
Some linters graph class relations and protocol dependency. Analyzing the collaboration graph we can infer rules and hints.
Tags
- Coupling
Conclusion
If two classes are too related and don't talk much to others we might need to split, merge or refactor them, Classes should know as little about each other as possible.
Relations
More Info
%[https://wiki.c2.com/?InappropriateIntimacy]
https://refactoring.guru/es/smells/inappropriate-intimacy
https://www.thecodebuzz.com/awesome-code-inappropriate-intimacy-code-smell-resolution/
Credits
Photo by Becca Tapert on Unsplash
No matter how slow you are writing clean code, you will always be slower if you make a mess.
Software Engineering Great Quotes
This article is part of the CodeSmell Series.