Showing posts with label Fluent Decorator. Show all posts
Showing posts with label Fluent Decorator. Show all posts

Monday, August 27, 2012

Fluent validations using the fluent decorator pattern


Validation on business objects is a responsibility that changes based on the requirements and sometimes gets added or removed based on the context.  The decorator design pattern can be utilized to provide various validations on business objects which can be attached to the object dynamically. In this post we’ll see how we can use the fluent decorator to implement fluent validations on an entity. We’ll create the base validate as a generic class so that it can be used on any entities in the application.
public class Order
{
    public string OrderNumber { get; set; }
    public int OrderId { get; set; }
    public string Description { get; set; }
    public Customer Customer { get; set; }
    public DateTime OrderDate { get; set; }
    public string ShipmentDetails { get; set; }
    public DateTime? RecievedDate { get; set; }
    public OrderStatus Status { get; set; }
}
We’ll be using the Order object and validate it in this sample.
The interface IEnityValidator is used as the signature for our validation objects.
public interface IEntityValidator
{
    bool Validate();
    string GetErrorMessage();
    bool IsValid();
    List<ValidationError> GetErrors();
}

public class ValidationError
{
    public ValidationError(string field, string message)
    {
        Field = field;
        Message = message;
    }

    public string Field { get; set; }
    public string Message { get; set; }
}

The abstract EnityValidationDecorator is the base class for the validation decorators. All our decorators will inherit this class and implement the Validate method to do validations on the object passed to the validator.
public abstract class EntityValidationDecorator : IEntityValidator
{
    protected T _Entity;
    protected IEntityValidator _Validator;
    protected StringBuilder _messageBuilder = new StringBuilder();
    protected List<ValidationError> _Errors = new List<ValidationError>();

    protected EntityValidationDecorator(IEntityValidator validator)
    {
        var entityValidator = validator as EntityValidationDecorator;
        if (entityValidator != null) _Entity = entityValidator._Entity;

        _Validator = validator;
    }

    protected EntityValidationDecorator(T entity, IEntityValidator validator)
    {
        _Entity = entity;
        _Validator = validator;
    }

    public abstract bool Validate();
    public abstract string GetErrorMessage();
    public List<ValidationError> GetErrors()
    {
        if (_Validator == null) return _Errors;
        _Errors.AddRange(_Validator.GetErrors());
        return _Errors;
    }
       
    public abstract bool IsValid();
}
Implementing the Order number validator.
public class OrderNumberValidator : EntityValidationDecorator<Order>
{
    public OrderNumberValidator(IEntityValidator validator) : base(validator)
    {
    }

    public override bool Validate()
    {
        _Validator.Validate();
        string validationMessage;
        var orderNumber = _Entity.OrderNumber;

        if(string.IsNullOrEmpty(orderNumber))
        {
            validationMessage = "Order number cannot be empty";
            GetErrors().Add(new ValidationError("OrderNumber", validationMessage));
            _messageBuilder.AppendLine(validationMessage);
            return false;
        }
        if(orderNumber.Length < 5)
        {
            validationMessage = "Order number should be greater than 5";
            GetErrors().Add(new ValidationError("OrderNumber", validationMessage));
            _messageBuilder.AppendLine(validationMessage);
            return false;
        }
        return true;
    }

    public override string GetErrorMessage()
    {
        return string.Concat(_Validator.GetErrorMessage(), _messageBuilder.ToString());
    }

    public override bool IsValid()
    {
        return !GetErrors().Any();
    }
}
Similarly we can use different kinds of validators for performing validations on our Order object. Later we can add fluent interface support to the validations by using extension methods as given below.
public static class OrderDecoratorExtensions
{
    public static EntityValidationDecorator<Order> AttachValidator(this Order order)
    {
        return new OrderValidator(order);
    }

    public static EntityValidationDecorator<Order> AddOrderNumberValidation(this EntityValidationDecorator<Order> validator)
    {
        return new OrderNumberValidator(validator);
    }

    public static EntityValidationDecorator<Order> AddOrderCustomerValidation(this EntityValidationDecorator<Order> validator)
    {
        return new OrderCustomerValidator(validator);
    }

    public static EntityValidationDecorator<Order> AddOrderDateValidation(this EntityValidationDecorator<Order> validator)
    {
        return new OrderDateValidator(validator);
    }
}
Testing the validators.
[TestMethod]
public void OrderNumberShouldNotBeEmpty()
{
    var order = new Order();
    var orderValidator = order.AttachValidator()
        .AddOrderNumberValidation()
        .AddOrderCustomerValidation()
        .AddOrderDateValidation();

    var isValid = orderValidator.Validate();
    var errorMessage = orderValidator.GetErrorMessage();
    Assert.IsTrue(errorMessage != string.Empty);
    Assert.IsFalse(isValid);
}

Thursday, August 23, 2012

Refactoring inheritence explosion to fleunt decorator


The decorator pattern is used to extend or alter the functionality of an object at runtime. IT does this by wrapping the object with a decorator class, leaving the original object intact without modification. Let’s look into the code structure given below for a Starbucks coffee menu implementation for calculating the cost of the beverages including the various coffee toppings provided. An inheritance based approach will result in an object explosion like this.

We can try to reduce the complexity of this design by refactoring this to a decorator implementation. Later I’ll show how we can use fluent interfaces to create a fluent decorator that is more readable and a cleaner approach to use.  The final implementation changes our code structure to something like

We’ll start our refactoring task by creating a base class for our beverage decorator as given below.
public abstract class Beverage
{
    public string Name { get; set; }

    public abstract string GetDetails();
    public abstract int GetCalories();
    public abstract decimal GetCost();
    public abstract string GetDescription();
}
public abstract class BeverageDecorator : Beverage
{
    protected Beverage _beverage;

    protected BeverageDecorator(Beverage beverage)
    {
        _beverage = beverage;
    }

    public override string GetDetails()
    {
        var descriptionBuilder = new StringBuilder();
        descriptionBuilder.Append(_beverage.Name);
        descriptionBuilder.AppendLine(_beverage.GetDescription());
        descriptionBuilder.AppendFormat(" with : {0}", Name);
        descriptionBuilder.AppendLine();
        descriptionBuilder.AppendFormat("Costs : {0:C}", _beverage.GetCost() + GetCost());
        descriptionBuilder.AppendLine();
        descriptionBuilder.AppendFormat("Total calories : {0}g", _beverage.GetCalories() + GetCalories());
        descriptionBuilder.AppendLine(_beverage.GetDetails());
        descriptionBuilder.AppendLine(GetDescription());
        return descriptionBuilder.ToString();
    }
}
We include a protected Beverage member in our decorator to access it and apply extensions on the methods.
Next you can start creating the decorators for the coffee toppings. I’ve added a sample implementation for the whip cream decorator below
public class CreamDecorator : BeverageDecorator
{
    public CreamDecorator(Beverage beverage) : base(beverage)
    {
        Name = "Whip cream";
    }

    public override int GetCalories()
    {
        return 100 + _beverage.GetCalories();
    }

    public override decimal GetCost()
    {
        return _beverage.GetCost() + .50M;
    }

    public override string GetDescription()
    {
        return "Sweetened and flavored with vanilla.";
    }
}
You can now use the beverage object with added toppings as given below
[TestMethod]
public void DecoratorAddsFunctionalityAtRuntime()
{
    Beverage beverage = new CafeMisto();
    beverage = new CreamDecorator(beverage);
    beverage = new ChocolateFlakesDecorator(beverage);
    beverage = new CinnamonSprinklesDecorator(beverage);

    Assert.IsTrue(beverage.GetCost() > 2M);
    Assert.IsTrue(beverage.GetCalories() > 110);
}

Next we can use fluent interfaces approach by adding extension methods to the Beverage class as
public static class BeverageDecoratorExtensions
{
        public static Beverage AddCream(this Beverage beverage)
        {
            return new CreamDecorator(beverage);
        }

        public static Beverage AddChocolateFlakes(this Beverage beverage)
        {
            return new ChocolateFlakesDecorator(beverage);
        }

        public static Beverage AddCinnamonSprinkles(this Beverage beverage)
        {
            return new CinnamonSprinklesDecorator(beverage);
        }
}

After applying fluent interfaces our decorator implementation can be applied by using the syntax
[TestMethod]
public void DecoratorAddsFunctionalityAtRuntime()
{
    var beverage = new CafeMisto()
                        .AddCream()
                        .AddChocolateFlakes()
                        .AddCinnamonSprinkles();

    Assert.IsTrue(beverage.GetDetails().Contains("Whip cream"));
    Assert.IsTrue(beverage.GetCost() > 2M);
    Assert.IsTrue(beverage.GetCalories() > 110);
}