Category Archives: OOP

A short intro on .NET Design by Contract approach

During software development debugging we frequently dig into functions or code libraries and eventually find out that the arguments passed in the first place was mistaken. For example, here is a method using NHibernate repository pattern:

/// <summary>
/// Get the product by the given ID
/// </summary>
/// <param name="productId">The product ID should be a positive integer</param>
/// <returns></returns>
public Product GetProductById(int productId)
    ProductRepository productRepository = new ProductRepository();
    Product product = productRepository.GetById(productId);

    return product;

It happens so often that we fail to notice the comment when calling this method and get a null object from it. We then debug “Object reference not set to an instance of an object” error and figure out the ID should be a positive integer(not that easy to make such an apparent mistake though…). The problem is easy to spot here but not in a more complex method. By applying Design by Contract(DbC) approach the error can be instantly exposed and the method is more robust:
Read the rest of this entry »

Leave a comment

Posted by on August 5, 2012 in .NET, C#, OOP