Code Smell 61 — Coupling to Classes
Classes are handy. We can call them and invoke them any time. Is this good?
- Hard to mock
- Use interfaces or traits (if available).
- Use Dependency Injection.
- Favor Loose Coupling.
We can use almost any linter to find references to classes. We should not abuse since many uses might be false positives.
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.
Code Smell 30 — Mocking Business
Mocking is a great aid when testing behavior. Like with many other tools, we are abusing them.
Coupling: The one and only software design problem
A root cause analysis of all failures of our software will find a single culprit with multiple costumes.
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.
This article is part of the CodeSmell Series.