Skip to main content

Command Palette

Search for a command to run...

Code Smell 61 - Coupling to Classes

Published
3 min read
Code Smell 61 - Coupling to Classes
M

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.

Classes are handy. We can call them and invoke them any time. Is this good?

Problems

  • Coupling

  • Extensibility

  • Hard to mock

Solutions

  1. Use interfaces or traits (if available).

  2. Use Dependency Injection.

  3. Favor Loose Coupling.

Sample Code

Wrong

Detection

We can use almost any linter to find references to classes. We should not abuse since many uses might be false positives.

Tags

  • Coupling

Conclusion

Dependencies to Interfaces make a system less coupled and thus more extensible and testable.

Interfaces change less often than concrete implementations.

Some objects implement many interfaces, declaring which part depends on which interface makes the coupling more granular and the object more cohesive.

Relations

More info

Credits

Photo by Marco Bianchetti on Unsplash


When your code depends on an interface, that dependency is usually very minor and unobtrusive. Your code doesn’t have to change unless the interface changes, and interfaces typically change far less often than the code behind them. When you have an interface, you can edit classes that implement that interface or add new classes that implement the interface, all without impacting code that uses the interface.

For this reason, it is better to depend on interfaces or abstract classes than it is to depend on concrete classes. When you depend on less volatile things, you minimize the chance that particular changes will trigger massive recompilation.

Michael Feathers



This article is part of the CodeSmell Series.

T

I am learning a lot by following the series. To be honest, I have not internalized all of it but I understand most of it and try to find references in the code. Good Job, Maxi Contieri.

C

You are doing a great job with this series. Nice article as always, Maximilian! 😊

1

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.