Tag-Archive for ◊ Design Patterns ◊

Author:
Saturday, March 23rd, 2013

Design patterns are reusable solution to software development issues. It was introduced by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Gang of Four). We can say that they are recurring solutions to common S/w development challenges.

Using design patterns on your application it is very easy to encapsulate your ideas. Design patterns are not specific to any language. However it does depend on capabilities of the language.

You really wont realize the use of design patterns using small examples. It often come into play when there is large code bases .

Since PHP being opensource a lot of PHP developers dont usually follow these principles of Software development. Also these patterns will be in built in Opensource php frameworks , but we hardly know what is happening .

Design patterns are basically classified into 3 kinds

Design-Patterns-Categories

 

 

 

 

 

 

 

 

 

 

 

They are :

  1. Structural
  2. Creational
  3. Behavioral

Structural patterns deals with the relation ship between entities .

Creational patterns creates objects for you, and you can use this objects in a manner that suits your situation.

Behavioral patterns is used in communication between entities and makes it easy for these entities to communicate with each other .

Friday, September 28th, 2012
FactoryGirl is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class including factory inheritance. James Kovacs has created a nice implementation of the FactoryGirl class in .NET. You can follow this link to check out his article on implementing the FactoryGirl in .NET. I have extended the FactoryGirl implementation by using Moq to register and invoke stubs to use in unit test methods.
public class FactoryGirlStubs
{
private static readonly IDictionary<Type, object> stubs = new Dictionary<Type, object>();
public static IEnumerable<Type> DefinedStubs
{
get { return stubs.Select(x => x.Key); }
}
public static void ClearStubDefinitions()
{
stubs.Clear();
}
public static void ClearStub()
{
stubs.Remove(typeof(T));
}
public static T BuildStub() where T : class
{
var result = (T)stubs[typeof(T)];
return result;
}
public static void DefineStub() where T : class
{
var mock = new Mock();
mock.SetupAllProperties();
if (stubs.ContainsKey(typeof(T))) throw new DuplicateStubException();
stubs.Add(typeof(T), mock.Object);
}
public static void DefineStub(Expression<Action> expression) where T : class
{
var mock = new Mock();
mock.Setup(expression);
mock.SetupAllProperties();
if (stubs.ContainsKey(typeof(T))) throw new DuplicateStubException();
stubs.Add(typeof(T), mock.Object);
}
public static void DefineStub(Expression<Func> expression, TResult result) where T : class
{
var mock = new Mock();
mock.Setup(expression).Returns(result);
mock.SetupAllProperties();
if (stubs.ContainsKey(typeof(T))) throw new DuplicateStubException();
stubs.Add(typeof(T), mock.Object);
}
}

Test methods
[TestMethod]
public void DefineAddsTheStubsToTheStore()
{
FactoryGirlStubs.DefineStub<ICustomerRepository>();
Assert.IsTrue(FactoryGirlStubs.DefinedStubs.Any(x => x.Name.Contains(“ICustomerRepository”)));
FactoryGirlStubs.ClearStubDefinitions();
}
[TestMethod]
public void BuildShouldReturnTheDefinedStubFromStore()
{
FactoryGirlStubs.DefineStub<ICustomerRepository>();
var repository = FactoryGirlStubs.BuildStub<ICustomerRepository>();
Assert.IsInstanceOfType(repository, typeof(ICustomerRepository));
FactoryGirlStubs.ClearStubDefinitions();
}
[TestMethod]
public void DefineWithSetupRegistrationsShouldReturnResultwhenSetupMethodIsInvoked()
{
FactoryGirlStubs.DefineStub<ICustomerRepository, Customer>(x => x.GetById(1), new Customer { FirstName = “Prajeesh”
});
var repository = FactoryGirlStubs.BuildStub<ICustomerRepository>();
Assert.IsTrue(repository.GetById(1).FirstName == “Prajeesh”);
FactoryGirlStubs.ClearStubDefinitions();
}
Category: .Net, Agile/Scrum | Tags:  | One Comment
Saturday, September 22nd, 2012

The NullReferenceException is the most commonly occurring bugs in any programming language.

Passing nulls from a method leaves the responsibility to check the validity of the response object to the callee object/ method which leaves the space of null reference exceptions. For example in the code given below, the method which calls the repository’s GetById method needs to make sure that the Customer object is a valid one before making the assertions.
[TestMethod]
public void GetCustomerReturnsCustomerWithIDFromDB()
{
var repository = new CustomerRepository(_dbContext);
const int customerId = 5;
var customer = repository.GetById(customerId);
if(customer != null) Assert.AreEqual(customer.Id, 5);
Assert.Inconclusive(string.Format(“Customer with Id {0} was not found in the context”, 5));
}
public Customer GetById(int id)
{
return _context.Customers.FirstOrDefault(x => x.Id == id);
}
Refactoring the code to a maybe pattern implementation will make the repository define the contract of GetById to return a Maybe object which the callee always expects.
public interface Maybe<out T>
{
bool HasValue { get; }
T Value { get; }
}
public class Some : Maybe where T : class
{
private T _value;
public Some(T value)
{
_value = value;
}
public bool HasValue { get { return true; } }
public T Value { get { return _value; } }
}
public class None : Maybe where T : class
{
public bool HasValue { get { return false; } }
public T Value { get { throw new MaybeException();} }
}
The GetById method signature now changes to
public Maybe<Customer> GetById(int id)
{
var customer = _context.Customers.FirstOrDefault(x => x.Id == id);
return customer == null ? new None<Customer>() : new Some<Customer>(customer) as Maybe<Customer>;
}
Sunday, September 09th, 2012

In business applications, while creating searching algorithms you need to create a search context which consists of a combination of multiple algebraic expressions. A simple example is given below where the filter for searching books is created by combining multiple expressions as in the code sample below.

[TestMethod]
public void GetAllBooksInRangeByTopicShouldReturnAllBooksInThePriceRangeFilteredByTopic()
{
var amazonService = new BookStore();
const decimal fromRange = 50;
const decimal toRange = 100;
const string genre = “Travel Guide”;
var books = amazonService.GetBooksByPriceRangeAndGenre(fromRange, toRange, genre);
Assert.IsTrue(books.Any());
}
public IEnumerable<Book> GetBooksByPriceRangeAndGenre(decimal from, decimal to, string genre)
{
return GetAll().Where(x => x.Genre.Name.ToLower().Contains(genre.Trim().ToLower())
&& (x.Price >= from && x.Price <= to));
}
We can refactor these expressions to a more readable and maintainable structure by creating specifications using the interpreter pattern as given below.
public IEnumerable<Book> GetBooksByPriceRangeAndGenre(decimal from, decimal to, string genre)
{
var bookSpec = GetBookSpec(genre, from, to);
return GetAll().Where(bookSpec.SatisfiedBy());
}
private BookSpecification GetBookSpec(string genre, decimal from, decimal to)
{
return new BookSpecification(from, to, genre);
}
public class BookSpecification : ISpecification<Book>
{
private readonly decimal _from;
private readonly decimal _to;
private readonly string _genre;
public BookSpecification(decimal from, decimal to, string genre)
{
_from = from;
_to = to;
_genre = genre;
}
public Expression<Func<Book, bool>> SatisfiedBy()
{
return new GenreSpecification(_genre).AND(new PriceRangeSpecification(_from, _to)).SatisfiedBy();
}
}
public class GenreSpecification : ISpecification<Book>
{
private readonly string _genre;
public GenreSpecification(string genre)
{
_genre = genre.Trim().ToLower();
}
public Expression<Func<Book, bool>> SatisfiedBy()
{
return new Specification<Book>(x => x.Genre.Name.ToLower().Contains(_genre)).SatisfiedBy();
}
}
public class PriceRangeSpecification : ISpecification<Book>
{
private readonly decimal _from;
private readonly decimal _to;
public PriceRangeSpecification(decimal from, decimal to)
{
_from = from;
_to = to;
}
public Expression<Func<Book, bool>> SatisfiedBy()
{
return new Specification<Book>(x => x.Price >= _from && x.Price <= _to).SatisfiedBy();
}

}

Monday, August 27th, 2012
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 == nullreturn _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 23rd, 2012
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);
}
Category: .Net, Agile/Scrum | Tags:  | One Comment
Thursday, August 02nd, 2012

FluentAOP is a lightweight, fluent interface based library that allows implementing aspects of method interception in a simpler and easier way. FluentAOP is primarily designed to simplify the adoption and use of AOP in .NET. In contrast to most AOP implementations, its interception semantics exclusively rely on strongly-typed method definitions and a fluent API. Check this link for more details on method interception and AOP.

Creating the FluentAOP proxy is as easy as
return new Proxy<IEmployeeService>().Target(new EmployeeService()).Save();
The OnBefore and OnAfter methods can be used to execute some logic before and after the intercepted method is invoked for execution.
[TestMethod]
public void OnBeforeExecutesTheActionBeforeTheMethodIsCalled()
{
var service = EmployeeServiceFactory.Create();
var employees = service.GetAll();
Assert.IsTrue(employees.Any(e => e.Id == 10));
}
return new Proxy<IEmployeeService>()
.Target(new EmployeeService())
.InterceptMethod(m => m.GetAll())
.OnBefore(m =>
{
var service = m.Target as IEmployeeService;
if(service == null) throw new TypeAccessException();
service.Add(new Employee(10, “Test Employee”));
})
.OnAfter(m => Debug.WriteLine(string.Format(“Method called with argument {0}”, m.Arguments[0])))
.Save();
The OnInvoke method can be used to intercept the method call.
[TestMethod]
public void OnInvokeShouldInterceptTheActualMethodExecution()
{
var service = EmployeeServiceFactory.Create();
var employees = service.GetAll();
Assert.IsTrue(employees != null);
}
return new Proxy<IEmployeeService>()
.Target(new EmployeeService())
.InterceptMethod(m => m.GetAll())
.OnInvoke((m) =>
{
if(Cache.Instance.Exists(“Employees”))
return Cache.Instance.Get(“Employees”as IEnumerable<Employee>;
return m.Method.Invoke(m.Target, m.Arguments);
} )
.Save();
You can also use the OnReturn method to intercept the return value from the method and take actions based on the value.
[TestMethod]
public void OnReturnShouldBeCalledAfterTheInterceptedMethodExecutionCompletes()
{
var service = EmployeeServiceFactory.Create();
service.GetAll();
Assert.IsTrue(Cache.Instance.Exists(“Employees”));
}
return new Proxy<IEmployeeService>()
.Target(new EmployeeService())
.InterceptMethod(m => m.GetAll())
.OnReturn((m, r) =>
{
Cache.Instance.Update(“Employees”, r);
return r;
})
.Save();
Sunday, April 01st, 2012

The EventEmitter is the base building block for all compositions that would need to broadcast data to multiple consumers. Whenever there is an object that represents the source of several kinds of events, node.js usually makes the underlying class inherit from EventEmitter. The EventEmitter implementation makes use of the observer pattern by providing the ‘on’ function for objects that are interested in listening to an event. For e.g. you can listen to a specific event by calling the ‘on()‘ function on your object, providing the name of the event, as well as a callback closure as the

parameters.
eventEmitterInstance.once(‘event’, callbackSample1); //singular callback registration
//or
eventEmitterInstance.on(‘event’, callBackSample2); //multiple callback
Below given is a sample server implementation that logs the messages passed as querystring to the server using the EventEmitter implementation
var http = require(‘http’);
var port = process.env.PORT;
var server = http.createServer(function(request, response){
var eventEmitter = require(‘events’).EventEmitter;
var eventEmitterInstance = new eventEmitter();
var querystring = require(‘querystring’);
var message = querystring.parse(request.url).message;
var callbackSample1 = function(message)
{
console.log(‘logging from 1st callback function ‘ + message);
};
var callBackSample2 = function(message)
{
console.log(‘logging from 2nd callback function ‘ + message);
};
eventEmitterInstance.once(‘event’,
callbackSample1);
//singular callback registration
eventEmitterInstance.emit(message);
eventEmitterInstance.on(‘event’,
callBackSample2);
//multiple callback
eventEmitterInstance.emit(message);
eventEmitterInstance.emit(message);
eventEmitterInstance.removeListener(‘event’,
callBackSample2);
response.writeHead(200);
response.end(‘<html>’+
‘<head>’+
‘<meta http-equiv=”Content-Type”
content=”text/html; ‘
+
‘charset=UTF-8″
/>’
+
‘</head>’+
‘<body>’+
‘<form method=”post”>’ +
‘<h1>Messaging sample </h1>’ +
‘</form>’+
‘</body>’+
‘</html>’);
});
server.listen(port);
console.log(‘Server started….’);
As you can see, the on() function returns a reference to the object it belongs to, allowing you to chain several of such event listeners.  If you’re only interested in the first occurrence of an event, you can use the once() function instead. Finally, you can remove event listeners by using the removeListener function.
Friday, December 09th, 2011
Interceptor pattern can be used for addressing cross cutting
concerns in the application that happens at either the beginning or end of a
method. For e.g. checking the validity of the input parameters before executing
the method and throwing exceptions, catching and logging exceptions etc. These
situations can be encapsulated in a reusable component that can be processed by
the compiler and produce executable code (AOP).
Unity allows developers to implement the idea of
interception by allowing creation of objects that can add some extra code on
the target method before or after the regular execution of these target
methods. In this post, I’ll show how to create a Session handler for ASP.Net
using the interface interception mechanism provided by unity application block,
that will allow you to address encapsulate the logic for checking session for a
value before execution of the method and returning back the value from session
if available. The same handler can be used to also add the return value to the
session if not available so that this value can be retrieved next time.
Creating the session handler
public class SessionHandler : ICallHandler
{
private readonly string _sessionKey;
public SessionHandler(string
sessionKey)
{

_sessionKey = sessionKey;
}
public ISessionService
SessionService
{
get { return Container.Instance.Resolve<ISessionService>(); }
}
public IMethodReturn
Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (SessionService.Contains(_sessionKey))
{

input.CreateMethodReturn(SessionService.Get(_sessionKey));
return getNext()(input, getNext);
}
var returnValue = getNext()(input, getNext);
SessionService.Add(_sessionKey,
returnValue.ReturnValue);
return returnValue;
}
public int Order { get; set; }
}
The session handler uses the session service which
encapsulates the actual Session object to add/ remove values from the
session.  You can also use the
HttpContext.Current.Session object here.
Creating the Attribute for the handler
public class SessionDependencyAttribute : HandlerAttribute
{
private readonly string _sessionKey;
public SessionDependencyAttribute(string sessionKey)
{

_sessionKey = sessionKey;
}
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new SessionHandler(_sessionKey);
}
}
Creating a service and using the SessionHandler we created.
public interface IMockService
{
[SessionDependency("TestKey")]
string GetValue(bool
flag);
}
public class MockService : IMockService
{
public string
GetValue(bool flag)
{
return flag ? “True”
: “False”;
}
}
Configuring the Unity container
_container = new UnityContainer();
_container.AddNewExtension<Interception>();
_container

.RegisterType<ISessionService, SessionService>()

.RegisterType<IMockService, MockService>()

.RegisterType<MockPresenter>()
.Configure<Interception>().SetDefaultInterceptorFor<IMockService>(new
InterfaceInterceptor());
Test cases
[TestMethod]
public void
MethodShouldReturnValueFromSessionIfValueDoesNotExistsAndAddToSession()
{
var service = Container.Instance.Resolve<IMockService>();
var actual = service.GetValue(true);
Assert.IsTrue(SessionService.Contains(“TestKey”));
}
Monday, November 21st, 2011
In this post I’m going to create a generic implementation of
the specification pattern.
The central idea of Specification is to separate the
statement of how to match a candidate, from the candidate object that it is
matched against. As well as its usefulness in selection, it is also valuable
forvalidation and for building to order. Every specification implementation
needs to specify a method that evaluates a condition mentioned in the interface
Ispecification as given below.
public interface ISpecification where
T : class
{
Expression<Funcbool>> SatisfiedBy();
}
The generic specification class implements the Ispecification
interface as
public sealed class Specification
: ISpecification where T : class
{
readonly Expression<Funcbool>>
_matchingCriteria;
public Specification(Expression<Funcbool>>
matchingCriteria)
{
if (matchingCriteria == null)
throw new ArgumentNullException(“matchingCriteria”);

_matchingCriteria = matchingCriteria;
}
public Expression<Funcbool>>
SatisfiedBy()
{
return _matchingCriteria;
}
}
Using this implementation we can create the AND
specification as
public sealed class AndSpecification
: ISpecification where T : class
{
private readonly ISpecification _rightSideSpecification;
private readonly ISpecification _leftSideSpecification;
public AndSpecification(ISpecification
leftSide, ISpecification rightSide)
{
if (leftSide == null)
throw new ArgumentNullException(“leftSide”);
if (rightSide == null)
throw new ArgumentNullException(“rightSide”);

_leftSideSpecification = leftSide;

_rightSideSpecification = rightSide;
}
public ISpecification
LeftSideSpecification
{
get { return
_leftSideSpecification; }
}
public ISpecification
RightSideSpecification
{
get { return
_rightSideSpecification; }
}
public Expression<Funcbool>>
SatisfiedBy()
{
var left = _leftSideSpecification.SatisfiedBy();
var right = _rightSideSpecification.SatisfiedBy();
return (left.And(right));
}
}
The AND method is an extension method on the ISpecification and
Expression<Funcbool>>
types
public static ISpecification AND(this ISpecification
leftSpecification, ISpecification
rightSpecification) where T : class
{
return new AndSpecification(leftSpecification,
rightSpecification);
}
public static Expression Compose(this Expression
first, Expression second,
Func<Expression,
Expression, Expression>
merge)
{
var map =

first.Parameters.Select((f, i) => new
{f, s = second.Parameters[i]}).ToDictionary(p => p.s, p => p.f);
var secondBody = ExpressionTreeParameterReplacer.ReplaceParameters(map,
second.Body);
return Expression.Lambda(merge(first.Body,
secondBody), first.Parameters);
}
public static Expression<Funcbool>> AND(this Expression<Funcbool>>
first,

Expression<Funcbool
>> second)
{
return first.Compose(second, Expression.And);
}
The ExpressionTreeVisitor implementation to replace and join
the parameters for these extension methods
public sealed class ExpressionTreeParameterReplacer
: ExpressionVisitor
{
private readonly Dictionary<ParameterExpression,
ParameterExpression> _map;
public ExpressionTreeParameterReplacer(Dictionary<ParameterExpression,
ParameterExpression> map)
{
_map
= map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression,
ParameterExpression> map,

Expression exp)
{
return new ExpressionTreeParameterReplacer(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression
p)
{
ParameterExpression replacement;
if (_map.TryGetValue(p, out
replacement))
p
= replacement;
return base.VisitParameter(p);
}
}
Now let’s look at a sample using the specification pattern
implementation.
public class Customer
{
public string
FirstName { get; set;
}
public string
LastName { get; set;
}
public string
UserName { get; set;
}
public DateTime
DateOfJoining { get; set;
}
public Address
Address { get; set;
}
}
public class Address
{
public string Street
{ get; set; }
public string State {
get; set; }
public string City { get; set; }
public string Country
{ get; set; }
}
public class CountryNameSpecification : ISpecification<Customer>
{
private readonly string _countryName;
public CountryNameSpecification(string countryName)
{

_countryName = countryName;
}
public Expression<Func<Customer,
bool>> SatisfiedBy()
{
return new Specification<Customer>(c
=> c.Address.Country.Contains(_countryName)).SatisfiedBy();
}
}
public class CustomerFirstNameSpecification :ISpecification<Customer>
{
private readonly string _firstName;
public
CustomerFirstNameSpecification(string
firstName)
{

_firstName = firstName;
}
public Expression<Func<Customer,
bool>> SatisfiedBy()
{
return new Specification<Customer>(c
=> c.FirstName.Equals(_firstName)).SatisfiedBy();
}
}
[TestMethod]
public void
AndSpecificationShouldSatisfyIfBothExpressionsSatisfiesTheCondition()
{
var customers = GetAllCustomers();
var fooCountrySpecification = new CountryNameSpecification(“Foo”);
var customerFirtNameSpecification = new CustomerFirstNameSpecification(“Foo4″);
var andSpecification =
fooCountrySpecification.AND(customerFirtNameSpecification);
var results =
customers.Where(andSpecification.SatisfiedBy());
Assert.IsTrue(results.ToList().All(c =>
c.Address.Country.Contains(“Foo”)
&& c.FirstName.Equals(“Foo4″)));
}
[TestMethod]
public void
OrSpecificationShouldSatisfyIfOnOfTheConditionsSatisfiesTheSet()
{
var customers = GetAllCustomers();
var fooCountrySpecification = new CountryNameSpecification(“Foo”);
var abcCountrySpecification = new CountryNameSpecification(“Abc”);
var pqrCountrySpecification = new CountryNameSpecification(“Pqr”);
var orSpecification =
fooCountrySpecification.OR(abcCountrySpecification).OR(pqrCountrySpecification);
var results =
customers.Where(orSpecification.SatisfiedBy());
Assert.IsTrue(results.Count() ==
customers.Count());
}
Where GetAllCustomers return an Iqueryable resultset of
customers with addresses.
Category: .Net, Agile/Scrum | Tags: ,  | 3 Comments