Patterns,Principles and Programming.

Have been thinking about putting together a collection of Jump Start Tutorials on some core concepts on Programming, finally getting everything together

Design Patterns

Design Princples

Code Smells and Refactoring Techniques

 

Design Patterns : Strategy Pattern

Strategy Pattern lets you create a family of strategies (algorithm) encapsulated into separate interchangeable classes. In our example, we will consider a Client class which needs to invoke different sorting algorithm.

 

Let’s first create the contract interface for different Sorting algorithm.

public interface ISortStrategy
{
   void Sort(int[] ArrayToSort);
}

Now that we have our interface ready, let’s go ahead and implement different sorting algorithms based on it.[/code]

public class QuickSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Quick Sort");
  }
}

public class BubbleSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Bubble Sort");
  }
}

public class MergeSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Merge Sort");
  }
}

public class HeapSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
   Console.WriteLine("Executing Heap Sort");
  }
}

Now let’s head to our Client Class and Inject the Strategy, which would be used to sort the Array.

internal class Client
{

  private int[] _IntArray;

  public Client(int[] IntArray)
  {
    _IntArray = IntArray;
  }

  public void Sort(ISortStrategy Strategy)
  {
   Strategy.Sort(_IntArray);
  }
}

As you can see , the Client Class is devoid of any direct dependencies as well as any nasty conditional statements. Yes, its a good idea to do away with Conditional Statements , especially those long if-else or switch cases as it can increase the cyclomatic complexity of the code. The Strategy is injected directly in the client, which invokes it.

Complete collection of articles on Design Patterns can be found here

Caliburn.Micro #005 : Bootstrapper with MEF

Previously, we learnt how to use SimpleContainer to set up our IoC Containers. We would be now looking into making the application more loosely coupled by leveraging the MEF. Just like with SimpleContainer, we would be focusing on the basic steps while configuring the IoC – Registering the IoC Container with Caliburn Micro and then registering the Service bindings. Let’s go ahead override the necessary methods

private CompositionContainer _Container;

protected override object GetInstance(Type service, string key)
{
  string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;
  var exports = _Container.GetExportedValues(contract);
  if (exports.Any())
      return exports.First();
  else
      throw new Exception("Could not find the key");
}

protected override void BuildUp(object instance)
{
  _Container.SatisfyImportsOnce(instance);
}

protected override IEnumerable GetAllInstances(Type service)
{
  return _Container.GetExportedValues(AttributedModelServices.GetContractName(service));
}

We will now go ahead and register our Service Bindings. This is where things get interesting.

protected override void Configure()
{
  _Container = new CompositionContainer(
                new AggregateCatalog(AssemblySource.Instance.Select(x=> new AssemblyCatalog(x)).OfType())
                );
  var batch = new CompositionBatch();
  batch.AddExportedValue(new WindowManager());
  batch.AddExportedValue(new EventAggregator());
  batch.AddExportedValue(_Container);

  _Container.Compose(batch);
}

As seen in the code above, we are using the AssemblySource to parse the ViewModels in the Assembly.

That’s it in Bootstrapper, but do not forget to decorate your View Model class with [Export()] Attribute and Constructor with [ImportingConstructor]. (For injecting dependency)

[Export(typeof(IReport))]
public class ReportViewModel :Screen, IReport
{
  [ImportingConstructor]
  publicReportViewModel(IEventAggregator EventAggregator)
  {
    // Do Constructor tasks
  }
}

We will delve into EventAggregators later, but for the moment, consider it an example of how to inject a dependency in the constructor when working with MEF.

Code sample for this post can be found here. The complete list of tutorials on Caliburn.Micro can be accessed here