Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Code Smell 61 — Coupling to Classes

Maximiliano Contieri
Dev Genius
Published in
2 min readFeb 4, 2021
Photo by Marco Bianchetti on Unsplash

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

Right

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

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Maximiliano Contieri

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com

No responses yet

Write a response