You should not define too much behavior together
TL;DR: Split your interfaces
-
Interface Segregation Principle Violation
-
Coupling
-
Split the interface
-
Use composition instead of inheritance
The term "Fat Interface" emphasizes that the interface is overloaded with methods, including those that may not be necessary or used by all clients.
The interface violates the principle of segregating interfaces into smaller, more focused contracts.
interface Animal {
void eat();
void sleep();
void makeSound();
// This protocol should be common to all animals
}
class Dog implements Animal {
public void eat() { }
public void sleep() { }
public void makeSound() { }
}
class Fish implements Animal
public void eat() { }
public void sleep() {
throw new UnsupportedOperationException("I do not sleep");
}
public void makeSound() {
throw new UnsupportedOperationException("I cannot make sounds");
}
}
class Bullfrog implements Animal
public void eat() { }
public void sleep() {
throw new UnsupportedOperationException("I do not sleep");
}
public void makeSound() { }
}
interface Animal {
void move();
void reproduce();
}
// You can even break these two responsibilities
class Dog implements Animal {
public void move() { }
public void reproduce() { }
}
class Fish implements Animal {
public void move() { }
public void reproduce() { }
}
class Bullfrog implements Animal {
public void move() { }
public void reproduce() { }
}
[X] Manual
We can check the size of the interface protocol
- Cohesion
Favoring small, reusable code components promotes code and behavior reuse.
Code Smell 61 - Coupling to Classes
Code Smell 135 - Interfaces With just One Realization
Code Smells are my opinion.
Photo by Towfiqu barbhuiya on Unsplash
The best smells are something that's easy to spot and most of time lead you to really interesting problems. Data classes (classes with all data and no behavior) are good examples of this. You look at them and ask yourself what behavior should be in this class.
Martin Fowler
Software Engineering Great Quotes
This article is part of the CodeSmell Series.