Advertisement
pro_cessor

NULL Objects?

Mar 27th, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. // as noted here: http://dl.dropbox.com/u/7810909/docs/patterns/patterns/html/index.html#IntroduceNullObject
  2.  
  3. if (customer == null)
  4.     plan = BillingPlan.basic();
  5. else
  6.     plan = customer.getPlan();
  7.  
  8. First let it be noted that this is essentially a violation of Tell-Don't ask.
  9. I am fiddling with the privates of customer (his plan). But since
  10. nothing else is given, I will stay in the context.
  11.  
  12. My idea of a NULL Object might become clearer when more scope is visible.
  13.  
  14.  
  15. The customer must come from somewhere. Let's imagine something like a DB access:
  16.  
  17.  
  18.  
  19. // The customer needs to come from somewhere
  20. var customer = customer.named('Petersen');
  21.  
  22. if (customer == null)
  23.     plan = BillingPlan.basic();
  24. else
  25.     plan = customer.getPlan();
  26.  
  27. // Something needs to happen with the plan object.
  28. _billingService.Magic(plan);
  29.  
  30.  
  31. If the object is null, this would say that the pointer is targeting a nonexisting adress and the object does not exist. What we are trying to convey though is that the coustomer could not be found. I feel that neither option nor x == null really capture this information.
  32. So the idea of the null object is, that a polymorphic object will be returned. This could behave as follows:
  33.  
  34. class NoCustomerFound : Customer
  35. {
  36.     public NoCustomerFound(string name)
  37.     {
  38.         // If this object exists it's due to some semantic error
  39.         // This could be handled in here. The ctor could log these cases
  40.         Logger.log('A customer with the name of ' + name + 'does not exist. ');
  41.     }
  42.  
  43.     public Plan getPlan()
  44.     {
  45.         // Handle here why this exists.
  46.  
  47.         return BillingPlan.basic();
  48.     }
  49. }
  50.  
  51.  
  52. var customer = customer.named('Petersen');
  53. customer.getPlan();
  54. _billingService.Magic(plan);
  55.  
  56.  
  57. Like this it is guaranteed that there is always a customer. If at some point the existence of a null is allowed all adjacent functions using it would have to reimplement the nullcheck. The special object makes the special error case an explicit part of the domain and gives us one single point of change, where we can handle this case.
  58. This prevents nullchecks all over the place and allows for semantics that are close to our actual domain.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement