Tuesday, August 6, 2019

C# Null Object Design pattern

public Customer GetByPhoneNumber(string phoneNumber)
{
  return _customerRepository
         .List(c => c.PhoneNumber == phoneNumber)
         .FirstOrDefault();
}

Problem with null


var customer = GetByPhoneNumber(phone);
 //Why null check this break design principle 
int orderCount = customer != null ? customer.OrderCount : 0;
decimal totalPurchase = customer != null ? customer.TotalPurchase : 0m;

Create NotFound Object Property



public class Customer
{
  public static Customer NotFound = 
     new Customer() { OrderCount=0, TotalSales=0m };
 
  // other properties and behavior
}

Final outcome No Null checks required


var customer = GetByPhoneNumber(phone);
int orderCount =  customer.OrderCount ;
decimal totalPurchase =customer.TotalPurchase;

No comments :