Thursday, March 28, 2013

D is for...

D is for Dependency Inversion Principle.

This principle states two things. The first is that "high-level modules should not depend on a low-level modules." Instead, "both should depend on abstractions." The second is that "abstractions should not depend on details." In fact, "details should depend upon abstractions." This is a principle that I thought I understood until I sat down to write this post. It seems I was getting it slightly confused with Dependency Injection.

The idea is that changes made to low-level modules should not ripple up and disturb the high-level modules resting on top of them. The high-level module should depend in an abstraction, like an interface, instead of on a specific implementation of a low-level module. There is no way to eliminate ripples of change, but they can be confined to a minimum number of modules.

I will again be referring to my http server in this example. I keep coming back to Java to explain these principles because they are much easier to see with explicit interfaces.

In my server, I have a router that holds all of the possible routes that a request can take. This lives inside of and was also initialized by my server class. In order to make my server more flexible, I passed the router (complete with routes) into the server when the server was created. This is where I confused inversion with injection. I had merely altered the order in which the server and router objects were created. For my server, as it stands, this is good enough.

In order to truly invert the dependency, I would need to define a router interface and use that in the server. The interface to the router would be a part of the server and changes to the router should not affect the interface. Doing this would allow my server to remain unchanged even if I substituted an entirely new router in. In fact, I may have to make this change in the future. I'll wait until a real need arises though.

I feel as though I may have still gotten this one wrong, so please correct me if I am mistaken.

No comments:

Post a Comment