Code Smell 216 - Fat Interface

You should not define too much behavior together

TL;DR: Split your interfaces

Problems

  • Interface Segregation Principle Violation

  • Coupling

Solutions

  1. Split the interface

Context

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.

Sample Code

Wrong

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() { }
}

Right

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() { } 
}

Detection

[X] Manual

We can check the size of the interface protocol

Tags

  • Cohesion

Conclusion

Favoring small, reusable code components promotes code and behavior reuse.

Relations

Disclaimer

Code Smells are my opinion.

Credits

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


This article is part of the CodeSmell Series.