Archive

Posts Tagged ‘Net 3.5’

Tail recursion in C# & F#

June 8th, 2010 stiiifff No comments

I’m currently in the process of learning functional programming using the F# programming language. It’s a slow & long journey but I enjoy it and even though I’m not using it on any real project (yet), “It makes my C# better“. While learning F#, I came across a technique called Tail-recursion … this is something most of us have learned during our studies, but I’m not sure everybody is using it on a daily basis ;-)

I wasn’t really aware of the implications this could have at runtime if the compiler could recognize tail-recursive functions and optimize code for them (basically, generate a loop) : successive recursive calls don’t consume additional stack space and thus don’t eventually cause a StackOverflow exception (looking at the Call Stack debug window in Visual Studio shows that only 1 stack frame is being used).

It is very interesting to know that the F# compiler does optimize code when it encounters tail-recursive functions while the C# compiler (most of the time) doesn’t. So, basically, there is no limitation at the CLR level, it is mostly up to the compiler to optimize or not based on some heuristics. If the C# compiler is not on par with F# one (yet), some improvements have been made in the latest release (4.0).

If you’re interested by this topic, here is a list of very informative posts (.Net specific):

And if, like me, you are a newbie in functional programming but you are willing to learn (on the .Net platform with F#) I would recommend the following book : Programming F#

Categories: F#, Languages Tags: , ,

Future of programming languages

March 17th, 2009 stiiifff 2 comments

Very interesting presentation by Anders Hejlsberg.

Categories: DSL, F#, Languages, Parallelism Tags: , , , ,

DDD Specifications

June 24th, 2008 stiiifff 4 comments

Specifications is an interesting pattern as it allows reuse of expressions on entities for filtering, querying, validation … going further, it could also be used to present users with smart composite filters in the UI (instead of the usual 'type a filter value for this field').

I was thinking about writing a lenghty post on specifications but others have done it, and probably much better than I could, so … I'm just going to gather some links for you to dig deeper in what specifications are and what they can be used for.

Ok, the Specification pattern looks good … but is it really usefull ? Well, yes ;) If you combine it with a Linq-friendly Repository, it is indeed quite usefull:

SpecificationModel

SpecificationModel

Let me describe the various components that appear on this diagram:

  • ISpecification<TEntity>: This is the base interface for Specification. It has one method 'IsSatisfiedBy' that takes an entity (a class without any other specific constraint) as argument and return a bool indicating if the entity matches the specification or not.
  • ILambdaSpecification<TEntity>: A specialized base interface for Specifications expressed as a Lambda expression. It has members returning the Lambda expression, an equivalent Predicate and a String representation.
  • LambdaSpecification<TEntity>: The implementation class of ILambdaSpecification<TEntity>. Contains implicit conversion operators from & to an untyped Lambda expression.
  • IRepository<TEntity>: The base interface for a Linq-friendly repository … and as Specifications can be expressed as Lambda expressios (= ILambdaSpecification<TEntity>), they can also be used as query filters on the Repository.
  • LambdaSpecificationExtensions: Extension method that allows conversion of a Lambda expression to a ILambdaSpecification<TEntity>.

That's just the base model for Specifications and the link with Repositories. Other aspects such as specification compositions must be taken into account, Linq supporting natively some of the necessary capabilities. Advanced specification concepts such as Subsumtion & Partially satisfied specifications can be implemented if needed only (don't make things more complex than they need to be for your project).

I hope this little introduction on specifications gave you an idea of the level of expressivenes your domain model can reach when using named specifications & specifications-friendly repositories !!! ;)

Categories: DDD, Patterns Tags: , , , ,

Domain-Driven Design with Linq & ORM – Part 2

June 19th, 2008 stiiifff 2 comments

In my last post about DDD & Linq (1.5 month ago … oops), I showed the following piece of code:

ServiceLocator.Register<IUnitOfWorkFactory, NHibernateUnitOfWorkFactory>();

using (UnitOfWork.Start())
{
    ITransaction tx = UnitOfWork.Current.BeginTransaction(IsolationLevel.ReadCommitted);
    try
    {
        IRepository<Customer> cr = UnitOfWork.Current.GetRepository<Customer>();
        Customer customer = cr.FindOne(c => c.Id == "AROUT");
        customer.Address = "125 Hanover Sq.";
        cr.Save(customer);
        tx.Commit();
    }
    catch
    {
        if (tx != null) tx.Rollback();
    }
    finally
    {
        if (tx != null) tx.Dispose();
    }
}

After thinking about it, refactoring it 10 times, I sat down this morning and finally got it the way I wanted (don’t ask me why it took so long lol):

// Configure your favorite IoC container:
// - Register an IUnitOfWorkFactory
// - Register an IRepositoryFactory
// - Register a generic IRepository<TEntity>
//   (your container must support open generic types).
// - Configure your container to use the IRepositoryFactory
//   to create instances of the IRepository<TEntity> component
//   (your container must support factories).
// Once your IoC container is set up, configure it as the ServiceProvider
// (must implement the IServiceProvider interface or use a wrapper) for the ServiceLocator helper
ServiceLocator.ServiceProvider = container;

// Start a unit of work
using (IUnitOfWork uow = UnitOfWork.Start())
{
    // Get an instance of repository
    IRepository<Customer> cr = ServiceLocator.GetService<IRepository<Customer>>();

    // Retrieve data with a Linq query
    Customer customer = cr.FindOne(c => c.CustomerID == "AROUT");

    // Modify retrieved entity
    customer.Address = "000 Hanover Sq.";

    // Ask repository to save changes
    cr.Save(customer);

    // Mark the unit of work as complete to propagate changes to data source
    uow.Complete();
}

The re-worked IRepository<T> looks like this:

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    long Count();
    long Count(Expression<Func<TEntity, bool>> predicate);
    void Add(TEntity entity);
    void Add(IEnumerable<TEntity> entities);
    void Remove(TEntity entity);
    void Remove(IEnumerable<TEntity> entities);
    void RemoveAll();
    void RemoveAll(Expression<Func<TEntity, bool>> predicate);
    void Save(TEntity entity);
    void Save(IEnumerable<TEntity> entities);
    TEntity FindOne(Expression<Func<TEntity, bool>> predicate);
    IEnumerable<TEntity> FindAll();
    IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> QueryAll();
    IQueryable<TEntity> QueryAll(Expression<Func<TEntity, bool>> predicate);
}

I think it looks better ;) I currently have UoW & Repository factories for the following ORM:

  • NHibernate
  • ActiveRecord
  • LinqToSql
  • EntityFramework

The code is still very experimental, relies a lot of Castle Project‘s libraries (some might view it as a pro, others a con …), and I unfortunately don’t have much time to work more on it. If there is any interest for it, I might drop it online in its current state (basic samples, no unit test, code analysis spitting out a lot of warnings).

Feedback is welcomed. :)

Possible Improvements:

  • For simplification purpose, I might remove the dependency to a ‘ServiceProvider‘ and instead define a simple ‘UnitOfWork.Configure‘ method where we can specify the type of the IUnitOfWorkFactory & IRepositoryFactory.
  • Should the IUnitOfWork interface expose a ‘GetRepository<TEntity>‘ method to get rid of the ugly static call to ‘ServiceLocator.GetService<IRepository<T>>‘ ?

Domain-Driven Design with Linq & ORM

May 1st, 2008 stiiifff 2 comments

We all now that an ORM plays an important role in a DDD architecture … but it would be nice if we could write our Domain Model without being tightly coupled to our favorite ORM tool, especially the code we write in Repositories. Thanks to Linq, we already have a way to abstract our queries (our ORM 'just has to' support Linq, anyway that's a requirement for a good ORM nowadays). The other thing we should be able to abstract is the object, specific to each ORM, that is the interface with the persistence layer, that keeps track of the changes on entities, the 'context' or the 'session' object.

Well, most ORM tools are implementing similar Patterns, namely UnitOfWork, IdentityMap, LazyLoad … so it is fair to assume that it should be possible to build an abstract layer that would allow us to work at a higher level, and have providers for our favorite ORM tools.

Here is a sample from some early code I wrote:

ServiceLocator.Register<IUnitOfWorkFactory, NHibernateUnitOfWorkFactory>();

using (UnitOfWork.Start())
{
    ITransaction tx = UnitOfWork.Current.BeginTransaction(IsolationLevel.ReadCommitted);
    try
    {
        IRepository<Customer> cr = UnitOfWork.Current.GetRepository<Customer>();
        Customer customer = cr.FindOne(c => c.Id == "AROUT");
        customer.Address = "125 Hanover Sq.";
        cr.Save(customer);
        tx.Commit();
    }
    catch
    {
        if (tx != null) tx.Rollback();
    }
    finally
    {
        if (tx != null) tx.Dispose();
    }
}

The Repository interface, which makes heavy use of Linq to express query criterions, looks like this:

public interface IRepository<TEntity> where TEntity : class
{
    long Count();
    long Count(Expression<Func<TEntity, bool>> predicate);
    void Delete(TEntity entity);
    void Delete(IEnumerable<TEntity> entities);
    void DeleteAll();
    void DeleteAll(Expression<Func<TEntity, bool>> predicate);
    void Save(TEntity entity);
    void Save(IEnumerable<TEntity> entities);
    TEntity FindOne(Expression<Func<TEntity, bool>> predicate);
    IEnumerable<TEntity> FindAll();
    IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> ProjectAll();
    IQueryable<TEntity> ProjectAll(Expression<Func<TEntity, bool>> expression);
}

Wanna use LinqToSql or EntityFramework instead of NHibernate … well, that’s easy, just change the first line to:

ServiceLocator.Register<IUnitOfWorkFactory, LinqToSqlUnitOfWorkFactory>();

or

ServiceLocator.Register<IUnitOfWorkFactory, EntityFrameworkUnitOfWorkFactory>();

Nice isn’t it ? ;)
We can also have:

ServiceLocator.Register<IUnitOfWorkFactory, ActiveRecordUnitOfWorkFactory>();

or

ServiceLocator.Register<IUnitOfWorkFactory, EussUnitOfWorkFactory>();

Well, I think you get the point.
So, what you think ? Suggestions & remarks are welcome.

“Not invented here” disclaimer: This code is largely inspired and based on code from Castle Project & Rhino.Commons. I just generalized it.

“Pre-Pre-Pre-Pre-Pre Alpha code” disclaimer: This code is quite experimental, it is not (yet) fully unit-tested and doesn’t support (yet) all the capabilities of the different ORM tools presented here.

Microsoft TechDays 2008 in Paris … soon !

January 28th, 2008 stiiifff No comments

This year will be the second year I go to the Microsoft Techdays in Paris. I will only attend the sessions on the Monday as most of the subjects I have interest in are presented on that day.
Those sessions are part of the 'DNG Symposium', which is a conference organised by the french website DotNetGuru.org.

Here is the agenda:
09:30 – 10:30: Presentation session
11:00 – 12:00: Domain Driven Design
13:00 – 14:00: Introduction on Volta (by Eric Meijer)
14:30 – 15:30: Linq and Entity Framework
16:00 – 17:00: Resource Oriented Architecture (ROA)
17:30 – 18:30: .NET and Open Source : return on experience

See you there on the 11th of February !

Categories: DDD Tags: ,

My top 5 technologies for 2008

January 27th, 2008 stiiifff No comments

Those are the technologies I will definitely try to master in 2008, because they add a real value to the art of software development and allow developers / architects to work at a higher level (less dirty code on the hands lol):

1. Visual Studio DSL Tools : I recently got interested in Domain-Specific Development especially with the wonderfull Visual Studio DSL Tools. Definitely have to practice this more. Guess I will order the book 'Domain-Specific Development with Visual Studio DSL Tools'.
2. WCF : The great (r)evolution that Microsoft delivered as part as .Net 3.0. Any .Net developer should know about it. Need to finish the book 'Programming WCF Services'.
3. WF : The 'unknown sibling' of WCF. I already have some advanced practice with that one (advanced custom activities) as I had a course & used it on a project for several months. Still have to finish reading the book 'Essential Windows Workflow Foundation'.
4. Linq : Definitely need to check the inner workins of Linq to gain a better understanding of it and be able to use it correctly with abstract Repositories & ORM.
5. DDD : Already got a good knowledge of that one, but I want to become an expert as it is gaining more & more popularity as well as visibility while Microsoft is adopting it slowly but surely (Linq to SQL, Entity Framework). 'Applying Domain-Driven Design and Patterns: With Examples in C# and .NET' is a real eye-opener on the subject.

Well, it seems that my schedule for 2008 is already full :) lol

Categories: DDD, DSL, WCF, WF Tags: , , , , ,