DEV Community

Cover image for Code Smell 94 - Too Many imports
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3

Code Smell 94 - Too Many imports

If your class relies on too many others, it will be coupled and fragile. A long import list is a good indicator.

TL;DR: Don't import too much.

Problems

  • Coupling

  • Single Responsibility Principle violation

  • Low Cohesion

Solutions

  1. Break the class

  2. Hide intermediate accidental implementation

Sample Code

Wrong

import java.util.LinkedList;
import java.persistence;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException 
import java.util.Queue;
import org.fermi.common.util.ClassUtil;
import org.fermi.Data;
//We rely on too many libraries

public class Demo {
   public static void main(String[] args) {

   }
}
Enter fullscreen mode Exit fullscreen mode

Right


import org.fermi.domainModel;
import org.fermi.workflow;

//We rely on few libraries
//and we hide their implementation
//So maybe transitive imports are the same
//but we don't break encapsulation

public class Demo {
   public static void main(String[] args) {

   }
}
Enter fullscreen mode Exit fullscreen mode

Detection

We can set a warning threshold on our linters.

Tags

  • Coupling

  • Ripple Effect

Conclusion

We need to think about dependencies when building our solutions to minimize Ripple Effect.

Relations

More Info

Credits

Photo by Zdeněk Macháček on Unsplash


Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it.

Alan Perlis


This article is part of the CodeSmell Series.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay