5 DI anti-patterns

 

In this chapter

  • Creating tightly coupled code with Control Freak
  • Requesting a class’s Dependencies with a Service Locator
  • Making a Volatile Dependency globally available with Ambient Context
  • Forcing a particular constructor signature with Constrained Construction

Many dishes require food to be cooked in a pan with oil. If you’re not experienced with the recipe at hand, you might start heating the oil, and then turn your back to read the recipe. But once you’re done cutting the vegetables, the oil is smoking. You might think that the smoking oil means the pan is hot and ready for cooking. This is a common misconception with inexperienced cooks. When oils start to smoke, they also start to break down. This is called their smoke point. Not only do most oils taste awful once heated past their smoke point, they form harmful compounds and lose beneficial antioxidants.

In the previous chapter, we briefly compared design patterns to recipes. A pattern provides a common language we can use to succinctly discuss a complex concept. When the concept (or rather, the implementation) becomes warped, we have an anti-pattern on our hands.

Definition

An anti-patters is a commonly occurring solution to a problem, which generates decidedly negative consequences, although other documented solutions that prove to be more effective are available.1

5.1 Control Freak

5.1.1 Example: Control Freak through newing up Dependencies

5.1.2 Example: Control Freak through factories

5.1.3 Example: Control Freak through overloaded constructors

5.1.4 Analysis of Control Freak

5.2 Service Locator

5.2.1 Example: ProductService using a Service Locator

5.2.2 Analysis of Service Locator

5.3 Ambient Context

5.3.1 Example: Accessing time through Ambient Context

5.3.2 Example: Logging through Ambient Context

5.3.3 Analysis of Ambient Context

5.4 Constrained Construction

5.4.1 Example: Late binding a ProductRepository

5.4.2 Analysis of Constrained Construction

Summary

sitemap