Simplicity equals elegance

Introduction

I have recently had to solve a massive problem do with architecting a next generation platform for a commercial product that will steer the development team now and into the future. This task has a history of failure and now I have stepped up to try a make things right. Some of the problems I needed to address was:

  • Architecture (to SOA or not to SOA)
  • Technology
  • Migration plan
  • Deployment

Retrospective

While brainstorming ideas about how to solve my particular problems, I went through a period of reflection. I questioned my self on all the practices that I would promote and the ones I would discard. I found this to be very healthy. Any good developer/architecture should regularly question their motives and approaches.

A lot of what we do its based on opinions, and sometimes based on other peoples opinions. I went about  eliminating the opinions that were not by own. For example “Persistent arrogance”:

  • Is this just an idealism?
  • What benefit does it give me?
  • What do I lose if I don’t have it?
  • Is this something at sounds great in theory but in practice it not achievable?
  • Is this something that someone has promoted to make them sound clever?

I did this over and over till I was happy that I had opinions that were my own. I reviewed programming and the industry in general and reflected on my own previous experience. One of the lessons I learnt was, it does not matter how clever someone is, what technologies you know or what pretty pieces of paper you have. Simple is best.

Just because its a dirty job doesn’t mean you need to get dirty!

I also find that top class developers generally make things complex and perceive that it is simple. Its worth having less junior developers around and present your code to them and get their feedback. Another trait that senior developers do it try to design and develop an elegance system, this leads to complexity, complexity leads to confusion, confusion leads to failure. The right thing to do it design and develop a system to be simply, then you get elegance.

What is Simple

Simple is relative, how do you measure simple? This is measured at many levels. The common place would be at code level.

Source code

Many books have been written about writing “Good” (again relative) code and writing Quality (relative again) code. Their are many things that make code “better” which makes it “simple” to understand and maintain: For example: (I have thought of many more points but a couple will do to illustrate the point)

  • Name classes, methods and variables correctly and meaningful.
  • Write methods that are small and concise.
  • Follow the OO principles (SOLID).
  • Use TDD with Test first design.

The next view would be how your code is structured and layered. If you have complex system that is all tackled up and depends on things that it shouldn’t, may be a few god objects and is a big sticky ball of mud. Then stretch it like a rubber band, pull the code about and separator it by the context that its used in. Of course, if you have a big ball of mud then I am pretty certain that you won’t have any unit tests that give you the feedback needed while you refactor. If you, like me have been unlucky and come to work on a code base that is a ball of sh** mess, then master refactorings and design patterns.

Technology

  • Is the technology the right tool for the job?
  • Are you using this tool, cos its someone above you tells you to?
  • Do you have alternatives?
  • How easy is it to recruit people with this skill?
  • Its the technology you are using, just geeky and looks got on your CV?

Technology has a big part to play in simple/complex contest. Its worth reviewing what you are are using.

Architecture

Does the architecture guide you or does it constrain you. Do you have read a book to understand the architecture that you are using? if an architecture is not flexible and you need to read a book about it then is not simple and not right.

Trends and fashion

This is linked to technology and my retrospective stated above. Developers my nature enjoy learning new technologies. Developers also try to find new smarts for the way they work. This is all great, but does need to be managed, otherwise your code base will be littered with spikes and random technologies. Before long your developers will not know what the standard tools or right the processes are. Technology and processes are in and out of fashion very quickly. A big dollop of common sense is required, review technologies and process in isolation and actually use the technology and try out a process rather than reading some blog and believing it.

Its easier to understand what is not simple.

Make it simple

“Simple” does have some concrete measures but their are other measures that are unique to you and your team. You need to identify what is important to you and analyse your code to see how it scores.  Making things simple it in my opinion, the most important design goal.

A point about Design patterns

I have heard people slate design patterns, i personally i love them, but some/alot of people misuse them and thats whats has started the negative press. The rule with design patterns to identify a pattern in the code not to put a patterns in the code that don’t fit. I find the power of patterns is the vocabulary. Its great describe a class’s purpose in life when stating its responsibility, for example “its an adapter” or “its a factory”. All things in moderation.

Conclusion

Keep it Simple. A easy principle to understand, but often the hardest to implement because out actions are to learn bigger more complex technologies and processes that keep pushing our careers to supposed new heights. It doesn’t matter how big someone’s brain is, can you develop code that is simple?

Advertisements

Creating Fluent finders and repositories part 1

Introduction

This is the first post of this series about implementing fluent finders and repositories, I am going to expand my current repository and finder implementation which is explained here. I recommend that you read this post (precursor) as this series continues on from this post and the code examples.

The objectives for this series are:

  • Create a fluent interface on the finders
    • Chain the find methods so that you can find on more than one method (method chaining).
    • Create an interface for sorting.
    • Create an interface for paginating the results.
  • Allow a service request (coarse grain) to be mapped to a specific fluent-interface call.
    • Based on information provided to a service as a request object, determine the right strategy for satisfying the request.
    • Execute the relevant strategy to perform the relevant queries
    • Return the query results to service method that was called.
    • The service method will return results as a response object.
  • Drive out these behaviours using TDD/BDD.

The outcome of this work will allow you write something like:

repository.find.ByThis(somevalue).AndFind.ByThat(someOtherValue).SortBy(aField, InAscendingOrder).Paginate.WithPageSize(10).ShowPage(1);

Before I start, one of the main benefits of a fluent interface is that you create an API that guides and limits the decisions that can be expressed in a logical order. So the interface needs to limit the options as the expression flows, which ultimately means you need to plan out the branching and the interfaces for each branch and decisions to ensure that public interface is meaningful to its context.

Table of Contents

Precursor

Part 1  (this post)

  • Refactoring the existing interfaces to provide interface segregation.
  • The Query Command
  • Method Routing
  • Method Chaining

Refactoring

Following on from the precursor, I need to stop my “IApplicationUserFinder” from implementing the “IEntityFinder” interface. The reason for this is the the  “IEntityFinder” interface exposes a property called DataSource. The published Fluent interface will want to expose the Find methods but not the DataSource property. So a bit of interface segregation is needed here to expose the right interface to the relevant consumer. While doing this refactoring, I decided that the name of the “IEntityFinder” is not right so I have renamed it to “IQueryableDataStore”. Although I have changed these interfaces around my concrete class  ApplicationUserFinder still need to implement both. So I have created yet another interface called “IQueryableApplicationUserFinder” which implements the “IQueryableDataStore” and “IApplicationUserFinder” interfaces. Now the ApplicationUserFinder class just implements IQueryableApplicationUserFinder. If I have scrambled your brain up, hopefully the code snipets below will make things clear.

    public interface IQueryableDataStore where Entity : EntityBase // was IEntityFinder
    {
        IQueryable DataSource { get; set; }
    }
...
    public interface IQueryableApplicationUserFinder :
        IApplicationUserFinder,
        IQueryableDataStore
    {
    }
...
 public class ApplicationUserFinder : IQueryableApplicationUserFinder
...

Now, how is this used. The ApplicationUserFinder is injected into the ApplicationUserRepository and then exposed via a getter (all by interfaces).  With the “IQueryableApplicationUserFinder” now in play, here is the revised code snippet for the repository (remember to change your IoC container to accommodate these changes).

    public class ApplicationUserRepository : EntityRepository,
        IApplicationUserRepository
    {
        private readonly IQueryableApplicationUserFinder finder;

        public ApplicationUserRepository(IPersistanceRepository repository,
            IQueryableApplicationUserFinder finder) : base(repository)
        {
            this.finder = finder;

            this.finder.DataSource = Query();
        }

        public IApplicationUserFinder Find
        {
            get { return finder; }
        }
    }

At this point, all my unit tests pass and application runs the same as it did before this refactoring.

The Query Command

Regardless of the expression that you can write using the fluent-interface, it needs  an end at some point. The Query Command objects is responsible for executing the query and return the result. I am using “Linq for objects” to write my queries and passing an IQueryable around under the covers, the execution of the queries is deferred until a method is called on it like “ToList()”. Calling the “ToList()” method will execute the underlying query.  I have  created a command object (based on the command pattern) to expose an “Execute” method that is going to return an IEnumerable<Entity>. The reason for returning “IEnumerable<Entity>” is that you have a vast about of extension methods that you use to execute the query. For example “ToList()” and “FirstOrDefault”. We can create the Query Command now and integrate it into the fluent-interface later with out much effort.

    public interface IQueryCommand where Entity : EntityBase
    {
        IEnumerable Execute();
    }

    public class QueryCommand : IQueryCommand
    {
        private readonly IQueryableDataStore queryableDataStore;

        public QueryCommand(IQueryableDataStore queryableDataStore)
        {
            this.queryableDataStore = queryableDataStore;
        }

        public IEnumerable Execute()
        {
            return queryableDataStore.DataSource.AsEnumerable();
        }
    }

So how can the fluent-interface get to this endpoint? Answer: we need an object to return it, so we can call it. I have defined this as “MethodRouter”.

Method Router

The method router exposes the actions that could be performed after a find method is called. As this is based on my previous post Implementing the Repository and Finder Pattern, I am going to change the original unit tests to drive out the method router. Here is the original specification for the “ApplicationUserFinder” class.

    [TestFixture]
    public class When_executing_queries_against_application_users
    {
        private ApplicationUserFinder finder; // subject under test

        [SetUp]
        public void Setup()
        {
            finder = new ApplicationUserFinder();

            finder.DataSource = GetStubbedCollection();
        }

        [Test]
        public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
        {
            ApplicationUser result = finder.ByLoginName("Test.User3");

            Assert.That(result.LastName, Is.EqualTo("User3"));
        }

        [Test]
        public void Should_return_a_user_by_token()
        {
            ApplicationUser result = finder.ByToken(Guid.Empty);

            Assert.That(result.LastName, Is.EqualTo("User2"));
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Should_fail_if_supplied_null_login_name()
        {
            IQueryable users = GetStubbedCollection();

            ApplicationUser result = finder.ByLoginName(null);
        }

        private IQueryable GetStubbedCollection()
        {
            List users = new List
            {
                new ApplicationUser { FirstName = "Test", LastName = "User1", LoginName="Test.User1", Token = Guid.NewGuid() },
                new ApplicationUser { FirstName = "Test", LastName = "User2", LoginName="Test.User2", Token = Guid.Empty},
                new ApplicationUser { FirstName = "Test", LastName = "User3", LoginName="Test.User3", Token = Guid.NewGuid()},
                new ApplicationUser { FirstName = "Test", LastName = "User4", LoginName="Test.User4", Token = Guid.NewGuid()},
                new ApplicationUser { FirstName = "Test", LastName = "User5", LoginName="Test.User5", Token = Guid.NewGuid()}
            };

            return users.AsQueryable();
        }
    }

As you can see from the above tests, each find method returns the result as a single domain entity. I now want to return an interface of the Method Router instead. The Method Router at point will expose the QueryCommand so that I still execute the queries and keep the code in a “close to working” state at all times.

To start with, I defined the MethodRouter interface “IApplicationUserFinderActions”

    public interface IApplicationUserFinderRouter
    {
        IQueryCommand Output { get; }
    }

Now, I need to change the return types in the IApplicationUserFinder to now return the IApplicationUserFinderRouter instead.

    public interface IApplicationUserFinder
    {
        IApplicationUserFinderRouter ByLoginName(string loginName);
        IApplicationUserFinderRouter ByToken(Guid token);
    }

At this point, things a little broken, so I need to change the concrete ApplicationUserFinder class to implement the changes made to the interface. To do this the concrete finder will need to know about the Method Router class. The method Router’s responsibility is to act as a hub to link object instances together. With this in mind, the MethodRouter class will need to know about the finder and the QueryCommand class. Still being mindful of the fluent interface and members it exposes, I need to ensure that the QueryCommand knows about the IQuerable instance held in the finder without coupling the objects together. To achieve this, I going to use the same technique I used in the Refactoring effort being the i return different interfaces to different parties. I have created another interface “IFindableApplicationUserFinderRouter” that implements IApplicationUserFinderRouter with an additional member.

Here is the new interface

    public interface IFindableApplicationUserFinderRouter
        : IApplicationUserFinderRouter
    {
        IQueryableApplicationUserFinder Finder { get; set; }
    }

Here is the concrete class ApplicationUserFinderRouter at this point.

    public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
    {
        private IQueryCommand queryCommand;

        public IQueryableApplicationUserFinder Finder { get; set;}

        public IQueryCommand Output
        {
            get
            {
                if (queryCommand == null)
                {
                    queryCommand = new QueryCommand(Finder);
                }

                return queryCommand;
            }
        }
    }

Here is the changed ApplicationUserFinder

    public class ApplicationUserFinder : IQueryableApplicationUserFinder
    {
        private readonly IFindableApplicationUserFinderRouter router;
        private IQueryable users;

	
        public ApplicationUserFinder(IFindableApplicationUserFinderRouter router)
        {
            this.router = router;
            this.actions.Finder = this;
        }
	

        public IQueryable DataSource
        {
            get { return users; }
            set { users = value; }
        }

        public IApplicationUserFinderRouter ByLoginName(string loginName)
        {
            if (string.IsNullOrEmpty(loginName))
            {
                throw new ArgumentNullException("loginName");
            }

	    
            users.Where(u => u.LoginName == loginName).FirstOrDefault();

            return router;
        }

        public IApplicationUserFinderRouter ByToken(Guid token)
        {
            users.Where(u => u.Token == token).FirstOrDefault();

		
            return router;
        }
    }

Here is a snippet of how one of the unit tests is looking.

	[SetUp]
        public void Setup()
        {
            router = MockRepository.GenerateStub();

            finder = new ApplicationUserFinder(router);

            finder.DataSource = GetStubbedCollection();
        }

        [Test]
        public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
        {
            ApplicationUser result = finder.ByLoginName("Test.User3").Output.Execute().FirstOrDefault();

            Assert.That(result.LastName, Is.EqualTo("User3"));
        }

At this stage is hard to see the advantage of this apart from separating out code. The next step is to allow the find methods to be chained together (method chaining).

Method Chaining

The IApplicationUserFinderRouter interface is going to allow the finder to be returned from a property. This is pretty simple stuff. Below is the interface with the new property and the concrete class implementing this addition member.

    public interface IApplicationUserFinderRouter
    {
        IQueryCommand Output { get; }
        IApplicationUserFinder AndFind { get; }
    }

    public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
    {
        private IQueryCommand queryCommand;

        public IQueryableApplicationUserFinder Finder { get; set;}

        public IQueryCommand Output
        {
            get
            {
                if (queryCommand == null)
                {
                    queryCommand = new QueryCommand(Finder);
                }

                return queryCommand;
            }
        }
	
        public IApplicationUserFinder AndFind
        {
            get { return Finder; }
        }
    }

This now allows the find methods to be chained so you can write the following code

        [Test]
        public void Should_return_a_user_when_finding_by_Login_name_and_token()
        {
            ApplicationUser result = repository
                .Find.ByToken(Guid.Empty)
                .AndFind.ByLoginName("Test.User2")
                .Output.Execute().FirstOrDefault();

            Assert.That(result.LastName, Is.EqualTo("User2"));
        }

That concludes this post, the next part of this series will cover paginating the results returned from the underlying query.

A recap on MV? pattern

I have my ever growing pet project that I have been playing about with for the last year. Its main purpose is a learning tool where I can try a few things out etc. I have been dabbling with the following view technologies.

  • WPF
  • Silverlight
  • Winforms
  • MonoRail
  • ASP.NET MVC

A common saying I here a lot is ” One Architecture can not fit them all”, this is very true. I learnt a long time ago, that development is not about technology, its about principles and practices. I follow guidance from the OO and agile worlds. In these worlds, we have design patterns. The granddaddy pattern of them all is MVC. I have used MVC for years with varying technologies but mainly with winforms.

Although MVC as pattern is not technology driven, its fare to say that you would want to get the best out of the view technology that you are using. To do this, you have to use an MVC variation/implementation that suits that technology. For example, the best technology on the list above for data binding is WPF, so if you want to lever the data binding in WPF then implement either the MVVM / Presenter Model, Supervising controller patterns.

I started using WPF at first, and I admit, I got caught up in an implementation that brought the best out of WPF. I was quite pleased with myself. I used the MVVM pattern, used XAML throughout my views had no code behind (apart from implementing an interface so I could pull it from my IoC container).

Then along come silverlight 2.0 and I thought I would have a play. In was not nice, downsizing the data-binding, lack of commands etc. Bottom line, its  another technology, I had to implement another variation of MVC to get the best out of silverlight. This was of course was not desirable.

Although my project is purely for play time, I have no deadlines to meet, but I was getting frustrated with the little progress I have made over a number of weeks plus adding  up the learning time I was burning up with WPF and Silverlight. So I decided to help me bash some more code out and flush out my UI requirements I started to create my views in winforms. The tactic was to build a working prototype in winforms  and then revisit either silverlight or WPF at a later date and swap the views out.

Now by this time, I did not want to use the data binding in winforms (another story). So crack open another MVC implementation, this time I favoured Passive view (MVP). I wanted to keep my views as dumb as possible (which is good goal to have) and drive my views and presenter logic out using TDD. I found this to be the quickest pattern to code. In this pattern, the presenter tells the view what to do via an interface that the view implements. Although this means putting code in the code behind, I found that I was only using one line of code in each method and using simple property getters and setters.

On reflection of putting in winforms, I found that I was still getting the best from the technology and it felt cleaner. I am in good position now to plug in WPF again and keeping my presenters the same. But I have parked that idea for the time being while I build up some knowledge about ASP.NET MVC. I have been doing MonoRail development for the last 6 months so its not that strange to me.

Question: Do I want to develop new controllers and actions in ASP.NET MVC or reuse my existing presenters? Answer: its worth a go, and see if I integrated them to work with each other 😉

To conclude. The big thing that I have learned from this effort is to use the right patterns where needed and don’t be driven by technology, stick to patterns and concepts instead, because they last longer then any technology.

Implementing the Repository and Finder patterns

Introduction

Over the last year I have been developing my own application using Domain Driven Design (DDD). I am also working on products in my day job that uses DDD. In the last month, myself and my fellow developers that I work with, went on a little journey to find the right way to implement the repository pattern including queries. My fellow devs and I wanted a solution to achieve the following goals:

  • A solid OO approach that was not bound to a specific technology. Meaning that we could develop this in C# or Java or what ever language.
  • No leaky abstraction. For example, we are using nHibernate at the moment, but in the future we might choose to use a different Object Relational Mapper (ORM). We don’t want our Repository or Finder interface to expose Nhibernate interfaces like “ISession” or “ICriteria”.
  • A repository per aggregate root.
  • No code duplication
  • Fully testable, driven out by our unit tests and me able to mock out the dependancies.
  • Friendly to our Inversion of Control (IoC) framework (ninject, spring.net and castle Windsor etc)
  • Provide a fluent interface to our repositories.

None of us are new to the Repository pattern or ways to implement query objects, so we all have ideas and existing code for tackling this. Combined we come up with this.

In my own application, my implementation used extension methods, its worked well, but because extension methods are static, i had no way of mocking them out  with Rhino mocks. This was not a showstopper, but meant that when i was writing unit tests in my service layer for example i have to set up the data to satisfy the logic in the extension methods.

Throughout the rest of this post, i will be using code from my own application.

The desired result


Here is an example of how we intent to use our repositories:


ApplicationUser user = applicationUserRepository
    .Find.ByLoginName(request.LoginName);

As you can see the repository has a find property on it that exposes a  ByLoginName method that takes a string argument and returns a single ApplicationUser object.

Entity Implementation


The ApplicationUser is a Entity, all of my Entities inherit from a base class called EntityBase:

public abstract class EntityBase
{
    private int id; 

    protected EntityBase() : this(0) { } 

    protected EntityBase(int id)
    {
        this.id = id;
    } 

    public int Id
    {
        get { return this.id; }
    } 

    public abstract bool IsValid();

    ...
}

Not much to it this, all my entities have an identity and i want all my entities to be able to state if the data they contain is valid

Repository Implementation

All of my repositories extend a base IRepository interface.

public interface IRepository<T> where T : EntityBase
{
    T Get(int id);
    void Save(T entity);
}

As you can see the generic type is constrained by the EntityBase type. The IRepository interface is not used directly outside of my repository layer, but is extended by the typed Repository interfaces:

public interface IApplicationUserRepository : IRepository<ApplicationUser>
{
    IApplicationUserFinder Find { get; }
}

In my application, I use dependency injection so my repositories are injected using the typed interface.  IApplicationUserRepository has one member being the Finder interface (more on that below).

One of my objectives was to remove duplicate code, in my effort to do this, i have an abstract class in which all my repositories inherit from.

public abstract class EntityRepository<T> : IRepository<T> where T : EntityBase
{
    protected readonly IPersistanceRepository repository;

    public EntityRepository(IPersistanceRepository repository)
    {
       this.repository = repository;
    }     

    public virtual T Get(int id)
    {
       return repository.Get<T>(id);
    } 

    public virtual void Save(T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        } 

        if (entity.IsValid())
        {
             repository.Save(entity);
        }
    } 

     protected IQueryable<T> Query()
     {
         return repository.Query<T>();
     }

 }

This class must be supplied an instance of IPersistanceRepository.  Here is the IPersistanceRepository interface

public interface IPersistanceRepository
{
    T Get<T>(int id);
    void Save<T>(T entity);
    IQueryable<T> Query<T>();
}

A concrete implementation of the  IPersistanceRepository interface is the technology / ORM specific stuff. I am using NHibernate 2.0, so my concrete implementation is called “NHibernateRepository”. By using the IPersistanceRepository interface i am keeping the specifics abstracted away inside the concrete class. I have been able to successfully swap my IPersistanceRepository instance from NHibernate to a DB4o implementation with ease and no effect to my repositories.

Finder Implementation

Like the IRepository interface is used as a base interface, i also have a base IEntityFinder interface which again is not directly used outside of my repository layer.

public interface IEntityFinder<T> where T : EntityBase
{
    IQueryable<T> DataSource { set; }
}

As you can see, the interface has a DataSource property of IQueryable, the reason for this is that I am using System.Linq in my project which I will come onto later. But its purpose is to give the Finder a datasource. Now for the IApplicationUserFinder interface.

public interface IApplicationUserFinder : IEntityFinder<ApplicationUser>
{
    ApplicationUser ByLoginName(string loginName);

    ApplicationUser ByToken(Guid token);
}

The typed Repository

Now for my implementation of my typed Repository.

public class ApplicationUserRepository : EntityRepository<ApplicationUser>, IApplicationUserRepository
{
    private readonly IApplicationUserFinder finder; 

    public ApplicationUserRepository(IPersistanceRepository repository, IApplicationUserFinder finder)
        : base(repository)
    {
        this.finder = finder; 

        this.finder.DataSource = Query();
    } 

    public IApplicationUserFinder Find
    {
        get { return finder; }
    }
}

This repository derives from EntityRepository and implements IApplicationUserRepository. Its constucted with its dependencies being injected. The Finder instance has it datasource set to IQuerable<ApplicationUser>.

The typed finder

using System.Collections.Generic;
using System.Linq;

public class ApplicationUserFinder : IApplicationUserFinder
{
    private IQueryable<ApplicationUser> users; 

    public IQueryable<ApplicationUser> DataSource
    {
        set { users = value; }
    } 

    public ApplicationUser ByLoginName(string loginName)
    {
        if (string.IsNullOrEmpty(loginName))
        {
            throw new ArgumentNullException("loginName");
        } 

        return users.Where(u => u.LoginName == loginName).FirstOrDefault();
    } 

    public ApplicationUser ByToken(Guid token)
    {
        return users.Where(u => u.Token == token).FirstOrDefault();
    }
}

What do we have then

We have our entity, repository and Finder created. The repository and Finder have typed interfaces, which means i can wire these up in my IoC container. My IEntityFinder interface sort of went against my goal of no leaky abstraction as its using System.Linq, but i think i can live with myself. By having my finder implement an interface i could have different concrete implementations.

My finder is returning a single instance of ApplicationUser. I could have finder methods that return Iquerable that allows for method chaining etc. Plus i have not allowed for “And”, “Or” or “Not” as that is a different topic. But i have a base to work on.

nibernate repository

To be more code complete here is a snippet of my NHibernate repository that returns the initial query. I am using nhibernate 2.0 with nhibernate.linq.

    using System.Linq;
    using NHibernate;
    using NHibernate.Linq;

    public class NHibernateRepository  : IPersistanceRepository
    {
        private readonly ISessionLocator sessionLocator;

        public NHibernateRepository(ISessionLocator sessionLocator)
        {
            this.sessionLocator = sessionLocator;
        }

        public T Get<T>(int id)
        {
            ISession session = sessionLocator.ActiveSession();

            return session.Get(id);
        }

        public void Save<T>(T entity)
        {
             ...
        }

        public IQueryable<T> Query<T>()
        {
            var qry = from t in sessionLocator.ActiveSession().Linq()
                      select t;

            return qry.AsQueryable();
        }
    }

The beauty of this that the NHibernate specific code is in one place, my repositories and finders have no knowledge of nhibernate. In my finders, i am using linq for objects and lambda’s for my logic. Because i am using IQuerable, i can build up the query through my finders and the execution is deferred until i call a method like “ToList” or “First” etc. The queryProvider in nhibernate.linq builds the sql statement and hits the database once with the specific query.

Finally a big thank you to Neil Martin and Tim Escott for their involvement on this. Please read this post “Creating Fluent finders and repositories part 1 which continues from this post.

Overview of the ModelView – ViewModel (MVVM) pattern and data-binding

In my own learning of WPF or any technology that I learn, I use the same approach and design principles that I would for a technology I know inside out. I have used winforms for years and I would be modest to say I know how to design a winform application the right way. It would be the approach I would use if I was developing an application in java swing. I would at the forefront of my design use the “model view controller” (MVC) pattern. The MVC pattern has been around since I was born and has been discussed and debated to death over the years. MVC aside I would use a number of other design patterns that fit the  bill for concern situations. For example: I would use command objects to do certain actions which could be wired up to menu items and/or buttons.

Model View Controller

The MVC pattern is a compound pattern, meaning that MVC is made up of other design patterns used together. MVC is made up of the “Mediator” and the “Observer” patterns (I and not going to discuss the details of these patterns as I want to keep to the subject matter, for more information on this patterns I recommend the Gang of Four web site and I might put a post together in the future).

Although MVC is a well established pattern, I have read other blogs and stuff in forums and the opinion of what MVC is, is very mixed. MVC in the .NET world seems to have become more wide spread over recent years which is good but MVC is not just about “Separation of Concerns” which some people I have worked along side believe. I can not remember where I got this from but the rules I follow are:

  • Model = what it is.
  • View = what it looks like.
  • Controller = what it does.

MVC is a pattern and as such is a guideline and the implementations of the pattern vary. Variations of MVC exist like “Model-View-Presenter” (MVP) and “ModelView-ViewModel” (MVVM). In a very brief explanation:

MVC – The view sits at the top of the architecture, the controller sits below the view. The model sits below the controller. So the view knows about the controller, the controller knows the model. The view is notified when the model changes.

MVP – The controller is replaced with a presenter. The presenter sits at the same level as the view. The presenter listens to the events of both the view and the model and mediates the interactions between both the view and model.

MVVM – The controller is replaced with a view model. the view model sits below the UI layer. The view model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The view model pulls its data from the model(s) below.

I read a blog by Josh Smith on “the code project” once where he talked about MVC and WPF and he stated “lower the flamethrower”. I echo his comments.

If you put ten software architects into a room and have them discuss what the Model-View-Controller pattern is, you will end up with twelve different opinions. … Some of the purists out there will inevitably have qualms with what I refer to as “MVC”. Feel free to leave a flaming comment on the message board at the bottom of this Web page. I will gladly entertain different perspectives on what MVC means, but keep in mind that I do not care.

Data-binding

The word Data-binding used to bring back bad memories of using data-binding in older technologies. In Winforms .net 2.0, it was not perfect, it was ok for simple things like binding data grids and text boxes and drop down boxes but using a date time picker was painful. The .net framework contains a number of interfaces and classes (“system.componentmodel”) that allowed you to implement better data-binding support in your own objects.  Using a custom implementation of the observer pattern with a hybrid of the data-binding interfaces was more desirable in winforms. (the memories, the pain).

But in WPF, no need to be down about data-binding, because it is excellent. Though it has a learning curve.

Data-binding is in its own right an implementation of MVC. the view are the controls that are shown in UI. the model is the object you are binding to and the controller is the data-binding component. I think its important to think about data-binding in this way.

Why is MVVM different

I believe that MVVM pattern was developed by some Microsoft developers a few years ago when developing Expression Blend. The main difference with MVVM to MVC is that the ViewModel is built to serve the view and provide the view with the data and commands it needs. The viewModel is not a general object that could serve different views but is bespoke for each view. For the TDD’ers out there its easy to define the behaviour of a viewmodel and test using a test first approach. The ViewModel is a model for the view. And the real power comes in when you bind your ViewModel to your view in WPF.

The key thing to remember is that you have one and only one ViewModel per view. The view model communicates with the model (business logic, services whatever below it). The view does not need to know about any else in your architecture. Another major plus point is that you do not any code behind your view and the data-binding deals with the communication to the view model and what ever the view model exposes.

Thats it for a quick overview. I have a draft post that i am working on that will put this into concrete code.