Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Tuesday, April 16, 2013

Are you “fluent” in C#?

I’m starting a new codeplex project to build a fluent library for design patterns. For example let’s take those examples.
Here is how to build a chain of responsibility is a standard manner:
var command1 = new Command1();
var command2 = new Command2("Test");
command1.NextInChain = command2;
command1.Execute(null);
Here is the same construct in a fluent manner:
var chain = new ChainBuilder<ChainCommand>()
  .Add<Command1>()
  .Add<Command2>(() => new Command2("Test"))
  .Build();
chain.Execute(null);
Which one do you like the most? In my case I prefer the fluent way. Building a chain of responsibility in not that difficult if you have only a handful of element to chain, but if you have more it become boring to remember to link the previous element to the next. My builder take car of that for you. Because of “fluent” concept you always now what comes next. For exmaple the ChainBuilder class only expose some overload of Add and a Build method.
So if you like this way of thinking, join my codeplex project and give me your feedback about it.
See : http://fluentpatterns.codeplex.com/

Wednesday, September 30, 2009

Using Decorator (or Wrapper) Design Patterns to add Validation to an object

Context

In most cases when someone write about the Decorator pattern it is usually related to UI stuff. The most common example is adding “decoration” to a control, for example a scroll bar. But in my humble opinion, this is not the most useful usage of Decorator. The purpose this pattern is:

“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality”

Gang of Four

If you think about it, Validation is a responsibility and so it can be added by this pattern. Of course we can add the validation to the class itself or in its base class, but how would you reuse this validation across many unrelated objects and what if you object must derive from another base class?

Solution

Decorator The solution is the Decorator pattern. With this pattern we can add new responsibility to an object without changing its internals.

For simplicity purpose we will take a simple sample that anyone can understand but the concept shown here can apply to much more complex object.

Four our sample we will take a bank account. On this account we should be able to to money deposit and withdraw. The class diagram on the right illustrate this design.

Let’s start by defining our IAccount interface

namespace Model
{
   public interface IAccount {
       string AccountNumber { get; }
       decimal Balance { get; }
       bool Active { get; }
       void Deposit(decimal amount);
       void Withdraw(decimal amount);
       void Close();
   }
}

This simple interface will be the central abstraction of the system. The goal is to never depends on concrete class and this interface in enough to add a lot of functionality around an account.

Now here the interface implementation as an Account:

using System.Diagnostics;

namespace Model
{
   [DebuggerDisplay("Account = {_accountNumber}, Balance = {_balance}")]
   public class Account : IAccount
   {
       public string AccountNumber { get; private set; }
       public decimal Balance { get; private set; }
       public bool Active { get; set; }

       internal Account(string accountNumber, decimal balance)
       {
           AccountNumber = accountNumber;
           Balance = balance;
           Active = true;
       }

       public void Deposit(decimal amount)
       {
           if (OnBeforeDeposit())
               Balance += amount;
           OnAfterDeposit();
       }

       protected virtual bool OnBeforeDeposit()
       {
           return true;
       }

       protected virtual void OnAfterDeposit() { }

       public void Withdraw(decimal amount)
       {
           if (OnBeforeWithdraw())
               Balance -= amount;
           OnAfterWithdraw();
       }

       protected virtual bool OnBeforeWithdraw()
       {
           return true;
       }

       protected virtual void OnAfterWithdraw() { }

       public void Close()
       {
           if (OnBeforeClose())
               Active = false;
           OnAfterClose();
       }

       protected virtual bool OnBeforeClose()
       {
           return true;
       }

       protected virtual void OnAfterClose() { }
   }
}

If you expand the previous block of code you will see that the implementation of IAccount is only doing business stuff. There is no other responsibility in this class than the one that is meant for. We can clearly see “Template Method” design pattern here. All “OnSomething()” method are protected and any derided class can add implementation around the process. All “Before” method can cancel the process if the return value is false. This allow extension classes to add some specific behaviour.

But one of the main thing missing in this class is “validation”. We will use the decorator pattern to do that. A decorator class is a class thst implement all the member of an abstraction and forward all the calls to an internal instance of a real implementation that abstraction. In our case the abstraction is “IAccount” so we have to make a decorator that implement that interface.

namespace Model.Decorator
{
   public abstract class AccountDecorator : IAccount
   {
       private readonly IAccount _account;

       protected IAccount Account
       {
           get { return _account; }
       }

       protected AccountDecorator(IAccount account)
       {
           _account = account;
       }

       public string AccountNumber
       {
           get { return Account.AccountNumber; }
       }

       public decimal Balance
       {
           get { return Account.Balance; }
       }

       public bool Active
       {
           get { return Account.Active; }
       }

       public virtual void Deposit(decimal amount)
       {
           Account.Deposit(amount);
       }

       public virtual void Withdraw(decimal amount)
       {
           Account.Withdraw(amount);
       }

       public virtual void Close()
       {
           Account.Close();
       }
   }
}

As you can see the constructor of the decorator takes an instance of “IAccount”. All method forward their call to that instance. This base class simplifies the process of creating concrete decorator by allowing other decorator to implement some but not all members of the interface.

Now is the time to start implementing our validation class structure. For that purpose we will create a base validation class that will be responsible of applying the validation the IAccount instance.

using System.Collections.Generic;
using Model.Decorator;

namespace Model.Validator
{
   public abstract class AccountValidatorBase : AccountDecorator
   {
       protected abstract IEnumerable<IValidation> GetValidations(decimal amount);

       protected AccountValidatorBase(IAccount account) : base(account) {}

       protected void Validate(decimal amount)
       {
           foreach (var validation in GetValidations(amount))
               if (!validation.IsValid)
                   throw validation.Exception;
       }
   }
}

This simple base class define a “GetValidations” method that all derived class must override to add a list of validation to perform on method call.

Now to implement the “Deposit” validation we have to create this class:

using System.Collections.Generic;
using Model.Validation;

namespace Model.Validator
{
   public class AccountDepositValidator : AccountValidatorBase
   {
       public AccountDepositValidator(IAccount account) : base(account) {}

       protected override IEnumerable<IValidation> GetValidations(decimal amount)
       {
           return new List<IValidation>
           {
               new AmountGreaterThanZeroValidation(amount),
               new AmountShouldHaveOnlyTwoDecimals(amount),
               new AccountMustBeActiveValidation(Account),
               new DepositAmountNotExceedMaxValidation(Account, amount)
           };
       }

       public override void Deposit(decimal amount)
       {
           Validate(amount);
           Account.Deposit(amount);
       }
   }
}

This class is responsible for creating all validation instances. The “Deposit” method is overridden to call the base “Validate” method before doing the actual deposit.

To implement those validation we need to define the “IValidation” interface.

using System;

namespace Model.Validator
{
   public interface IValidation
   {
       bool IsValid { get; }
       Exception Exception { get; }
   }
}

Here is a sample implementation:

using System;
using Model.Validator;

namespace Model.Validation
{
   public class AmountGreaterThanZeroValidation : IValidation
   {
       public AmountGreaterThanZeroValidation(decimal amount)
       {
           Amount = amount;
       }

       public decimal Amount { get; set; }

       public bool IsValid
       {
           get { return Amount > 0; }
       }

       public Exception Exception
       {
           get { return new ArgumentOutOfRangeException("amount", Amount, "Deposit amount should be greater than 0."); }
       }
   }
}

All other validations used in “AccountDepositValidator” can be described the same way.

The last step is to create an actual “IAccount” that will implement all this stuff. To do that we will need a Bank class. A bank is responsible of creating account. It will also be responsible of decorating it with all necessary decorators.

using System;
using System.Collections.Generic;
using Model.Logging;
using Model.Validator;

namespace Model
{
   public static class Bank
   {
       static readonly SortedDictionary<string, IAccount> _accounts = new SortedDictionary<string, IAccount>();
       private static int _accountSequence = 1;

       public static IAccount CreateAccount(decimal balance)
       {
           string accountNumber = String.Format("A{0:0000}", _accountSequence++);
           IAccount account = new Account(accountNumber, balance);
           account = new AccountDepositValidator(account);
           _accounts[account.AccountNumber] = account;
           return account;
       }
   }
}

To illustrate this process in action here is a sequence diagram:

Validation with Decorator

  1. Call Bank.CreateAccount.
  2. The Bank instantiate an Account class.
  3. The Bank create an AccountDepositValidator and wrap Account with it
  4. The Bank return an instance of IAccount.
  5. Deposit is called on IAccount which is an instance of AccountDepositValidator
  6. AccountDepositValidator call Validate
  7. AccountDepositValidator call GetValidations to retrieve the list of validation to evaluate
  8. An AmountGreaterThaZeroValidation is created
  9. IsValid returns true
  10. AccountDepositValidator call base Deposit method
  11. Balance value is updated

Next

With all this in place the only thing left to do is to implement all the other validators for all method of “IAccount”.

Tuesday, February 17, 2009

Extension methods series: the basics

One the new thing in C# is extension methods. Extension methods are static method that works pretty much like an helper function but instead of passing the instance to act on as an argument the instance is a prefix to the method. It looks exactly like if the method is part of the type itself.

Of course because C# is a statically typed language we are not really adding new method to a type. Here is the trick. The following example is a classic case of helper function:

if (String.IsNullOrEmpty(instance))
{
	// ...
}

The method “IsNullOrEmpty” is static a member of type “String”. To use it we must call it by its type and then pass it an instance of that type. Here is an easy way transform this helper function into an extension method.

public static class StringExtensions
{
	public static bool IsNullOrEmpty(this string instance)
	{
	    return String.IsNullOrEmpty(instance);
	}	
}

One of the requirement to make extension methods is the class must be static. Notice the “this” keyword used on the first argument of the method. This tell the compiler which type this method is extending and what type it should be.

Now if we use this code it will look like this:

if (instance.IsNullOrEmpty())
{
	// ...
}

At compile time the condition will be replaced by “StringExtension.IsNullOrEmpty(instance)”. So extension method is just a compiler trick to facilitate the uses of helper function. Beside the fact that it is easier to use it is also more readable. That is the starting point to fluent interfaces.

Wednesday, February 11, 2009

Why ++ operator is not thread safe

Here is a quick hint on how to make your software thread safe. If you want to increment a member of your class you would probably do something like this:

public void NotSafe()
{
    val++;
}

Where val is a member of your class.But this is not thread safe. Doing this involve 4 operations:

  1. Loading the field and put it on the stack
  2. Putting 1 on the stack to increment by 1
  3. Calling add on the stack
  4. Storing the result in the field

Here is the corresponding IL:

.method public hidebysig instance void NotSafe() cil managed
{
    .maxstack 8
    L_0000: nop
    L_0001: ldarg.0
    L_0002: dup
    L_0003: ldfld int32 ClassLibrary1.Class1::val
    L_0008: ldc.i4.1
    L_0009: add
    L_000a: stfld int32 ClassLibrary1.Class1::val
    L_000f: ret
}

The problem is that anywhere between any of the 4 steps another thread can try to do the same thing. For example if a second thread pup in just after the first one is between step 1 and 2 they will both try to increment the same value and store it on the stack. To resolve this problem you can use a lock like this:

public void SafeLock()
{
    lock (valLock)
    {
        val++;
    }
}

But this will generate the following IL:

.method public hidebysig instance void SafeLock() cil managed
{
    .maxstack 3
    .locals init (
        [0] object CS$2$0000)
    L_0000: nop
    L_0001: ldarg.0
    L_0002: ldfld object ClassLibrary1.Class1::valLock
    L_0007: dup
    L_0008: stloc.0
    L_0009: call void [mscorlib]System.Threading.Monitor::Enter(object)
    L_000e: nop
    L_000f: nop
    L_0010: ldarg.0
    L_0011: dup
    L_0012: ldfld int32 ClassLibrary1.Class1::val
    L_0017: ldc.i4.1
    L_0018: add
    L_0019: stfld int32 ClassLibrary1.Class1::val
    L_001e: nop
    L_001f: leave.s L_0029
    L_0021: ldloc.0
    L_0022: call void [mscorlib]System.Threading.Monitor::Exit(object)
    L_0027: nop
    L_0028: endfinally
    L_0029: nop
    L_002a: ret
    .try L_000f to L_0021 finally handler L_0021 to L_0029
}

As you can see there is a lot more code involve to ensure thread safety, A quicker, faster an easier way to do this s to use Interlocked class. This class will use low level OS call to modify the member. Here’s how to use it:

public void Safe()
{
    Interlocked.Increment(ref val);
}

This will be render as two major IL steps:

  1. Load value from the field and put it on the stack
  2. Call Increment

Here is the IL representation of this:

.method public hidebysig instance void Safe() cil managed
{
    .maxstack 8
    L_0000: nop
    L_0001: ldarg.0
    L_0002: ldflda int32 ClassLibrary1.Class1::val
    L_0007: call int32 [mscorlib]System.Threading.Interlocked::Increment(int32&)
    L_000c: pop
    L_000d: ret
}

Now every time you will see something++ you will know that this is not thread safe and how to fix it.

Saturday, November 24, 2007

Passing anonymous to and from method's call

As posted by Alex James on Meta-Me blog.

T CastByExample(object o, T example)

So earlier today I was lamenting that an anonymous type can't be
shared between functions with
Wes Dyer, when he said "Well actually they can..."

Cue me learning something cool.

The first step is to create a seemingly innocent method:

    public static T CastByExample<T>(this object o, T example)
    {
        return (T) o;
    }
Seems innocent enough right? Well it is until you start using it with anonymous types. Imagine you had this function, that returns an anonymous type as object, because that is your only choice:
static object GetAnonymousType()
{
    return new { FullName = "Cosmo Kramer" };
}
Normally if you called this function anywhere you wouldn't be able to get at the anonymous type without using reflection... This is where CastByExample<T> comes to the rescue. If you know the shape of the anonymous type, you use that to do a CastByExample...
        object o = GetAnonymousType();

        //get the original anonymous type back again
        var v = o.CastByExample(new { FullName = "" });

        //Use the properties of the anonymous type initialized in another
        //function directly !!
        Console.WriteLine(v.FullName);

This works because when an anonymous type is used the compiler first checks that one with the same signature (i.e. all fields are the same name and type) hasn't already been used. If one has the same CLR type is used.

Hence if you pass in an example that is the same shape as the original anonymous type to the CastByExample(..) method will get you back to the original anonymous type... and var magic does the rest.

Nifty huh?

Wednesday, November 7, 2007