Vlad's blog

In programming veritas

Archive for June 2011

Specification pattern

leave a comment »

Specification pattern is intended to solve the problem of entities selection according to particular search criteria. The main idea is to move selection logic from class representing entity into individual specification class.
Let’s consider online bookstore application like Amazon. A book is represented by Book class that has Title, Price and ReleaseYear attributes.

public class Book
    private readonly List _offerings;

    public int Id { get; set; }
    public string Title { get; set; }
    public decimal Price { get; set; }
    public decimal ReleaseYear { get; set; }
    public IEnumerable Offerings { get { return _offerings; } }

Each Book might have one or more related Offering class instances. Offering stores information about quantity of books available at particular stock. There is one-to-many relationship between Book and Offering.

public class Offering
    public int Id { get; set; }
    public Book Book { get; set; }
    public string Address { get; set; }
    public int Quantity { get; set; }

There is the following search criteria defined.

  • Publication date in the specified range
  • Available in stock
  • Price in the specified range

The first thing that comes to mind is to add corresponding search methods in Book class. But this approach becomes inconvenient when amount of search criteria grows up. In this case probably the better solution is to move selection logic into separate specification class. In our example a specification is represented by IBookSpecification interface that declares single SatisfiedBy method. The method receives a collection of Book entities and returns a collection that satisfies particular search criteria.

public interface IBookSpecification
    IEnumerable<Book> SatisfiedBy(IEnumerable<Book> books);

Read the rest of this entry »

Written by vsukhachev

June 7, 2011 at 5:46 am

Posted in Development

Tagged with ,