A lot of times I found that null returned from a method goes unhandled.
The number of bugs seem to be more due to Null reference exception than any other. I was wondering if we could avoid these errors at class design. That was when I came accross the Null Object Pattern. I started reading through. Looks good. But we have to take care to make changes in the class that handles nulls each time we change the class itself.
Where interfaces are recommended in design, it is not used by all. My product is already complete. Is it ok, if I dig into the classes and add a class that handles nulls for each class? This would call for quite a lot of modifications now that my solution already has about 35 projects in it.
Is it possible to create a single method and have it called whenever any object is created or returned. Can I use extension methods, coupled with generics?
Lets see.
Image from: http://en.wikipedia.org/wiki/Null_Object_pattern |
This is how null object pattern is implemented. I'm trying the same with generics and extension methods concept.
Lets start with a class called ObjectPatterns which implements an Interface IObjectOperations
Class: ObjectOperations
Extension class
Although, Clean<T>() can throw an InvalidCast exception. It is obvious that we would know the type of object we are expecting from function.
Here's the main program.
In the above program, objNull is of type Operations. We would already know that at compile time and when we are writing the code. We are expecting an object of Operations Type. So I guess we need not worry about the invalid cast. I'm not saying the above method is completely a robust way. I have not tested it for many cases. But yes, we can use it.
There is a drawback with the above method. It expects a non-static class which will always have a parameterless constructor.
I need to solve that part.
Thanks for your informative articel .its very useful
ReplyDeletedot net training in velachery | dot net training in chennai
Welcome. Hope to add more.
Delete