Friday, September 9, 2011

Dependency Injection (DI) – How and Why

There are two ways to implement dependency injection (DI) – through the class's constructor or its property setter. In class's constructor or the setter, instead of passing in a concrete class type parameter, use an interface. This way, you can later pass in different class objects that implement this same interface. The decoupling between the class constructor / setter and a concrete type provides the needed flexibility and scalability.

With this design, your classes are more unit-testable. You can create a mock class to implement the same interface as the real one, and pass in the mock object to the constructor or the setter. In the mock class, instead of connecting to a physical database server, you can set sample values as you wish. However, this would not eliminate the necessities to do your integration testing by connecting to the real database later.

Overall, the usage of DI will make your class handle less and less dependencies with concrete types, thus make it much more scalable.

understanding NULL Pattern

It is easy to miss a NULL check in our code especially when the code is not fully tested. Will it be nice to call one object's property or method without checking if the object is NULL or not without throwing NullReferenceException? The answer is to implement NULL pattern.

How?

Creat an interface for your real and null-check classes. In the real class, do real implementations. In the other null-check class, put in same signatures as the real one, but with no code, or return some default values. The callers would interact with the interfaces only. If the object is null, by calling its method, the null-check class will just do nothing or return default values. As a result, your code would have lot less IF tests for NULL references, and look more elegant and compact. 

However, doing null pattern will create more work initially. 

Here is the useful reference where I learned all about this - http://sourcemaking.com/design_patterns/null_object