DEV Community

Matheus Rodrigues
Matheus Rodrigues

Posted on • Originally published at matheus.ro on

Design Patterns and Practices in .Net: Null Object and Special Case Object

In programming null is an awkward thing to deal with, when you return a variable and it’s possible to be a null, you have to remember to make null checks all around your code.

The null object and the special case object are patterns that try to reduce this type of boiler plate code.

A null object is an object that doesn’t have a referenced value, is an object with a default behavior. A behavior which represents a missing object.

Special case object is very similar to the null object, but it’s an improvement over the null object, because instead of creating a generic “missing object”, you are creating a more specialized object that can suit better your needs.

The goal of these two pattern is to return a null or a special case version of an object, instead of return a null reference.

Problem

Many times we caught ourselves making this type of check:

public Product GetProductById(int productId)
{
    Product product = _productRepository.GetProductById(productId);
    if(product == null)
        throw new Exception("Product Not Found");
    return product;
}

Continue Reading...

Latest comments (0)