Recognizing DIP Violations
What you'll learn: You'll learn how to spot code that breaks the Dependency Inversion Principle by tightly coupling high-level logic to concrete implementations.
What Makes Code Violate DIP?
Now that you understand DIP's benefits, you need to recognize when code doesn't follow it. DIP violations happen when high-level components directly depend on low-level, concrete implementations instead of abstractions.
Look for these red flags:
-
Direct instantiation of concrete classes – When your business logic creates specific implementation objects using
new ConcreteClass(), you've hardwired a dependency. -
Framework or library types in business logic – If your core application code directly references database libraries, web frameworks, or external APIs without an abstraction layer, you're coupled to those details.
-
Hard-to-test code – When you can't easily swap out components for testing (like replacing a real database with a test double), it's often because dependencies point the wrong direction.
The Smell Test
Think of DIP violations like hardwiring appliances directly into your walls. If your coffee maker is permanently wired in, you can't replace it without rewiring. Similarly, code that directly depends on concrete implementations can't be modified or extended without changing the dependent code itself.
Ask yourself: "Could I swap this dependency for a different implementation without editing this class?" If the answer is no, you likely have a DIP violation.
Common Examples
- A
PaymentProcessorthat directly creates aStripePaymentGatewayobject - A
ReportGeneratorthat imports and uses a specificMySQLDatabaseclass - Business rules that reference HTTP request objects from a web framework
Key Takeaway: DIP violations appear as tight coupling to concrete implementations—watch for direct instantiation, framework dependencies in business logic, and code that resists testing or change.