Archive

Author Archive

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: , ,

Random thoughts

May 18th, 2010 stiiifff 3 comments

I’ve been fairly busy lately, working on interesting things at work, getting ready for an imminent birth, preparing some sessions as well … and also, thinking about a dozen of blog posts I wouldn’t have time to write. So anyway, here’s a quick & dirty cheap list of ramblings, not sure if it’s gonna be of any use, but it’ll hopefully free up some memory slots in my brain :-)

  • Complex Data Model != Domain Model : don’t get the “Let’s do DDD because it’s trendy. And, woohoo, that CQRS thingie would look nice on my CV as well” tendency too quickly. Knowing when not to apply DDD is almost as important as knowing how to apply it properly.
  • WCF RIA Services : I played a bit with it at work … and I like it. It was designed to address 80% (more ?) of the needs of developers writing n-tiers Data-Driven applications (also known, in the .Net world, as ‘Business applications’), and it does … just that. And that’s good. Sure, it can be misused and it’s bad because it doesn’t use Pattern ‘Blah’ and it violates Rule ‘MoreBlah’, but you’re smart right, so you’ll know when to use it, and when not to. I’m just a bit annoyed that the attributes, I mean, data annotations, are scattered in 25 different namespaces. “Bah, just press ‘Alt-Enter’ dude, API design is so overrated these days”.
  • Agatha : Using it, works well, like it. I’m a fan, it’s WCF for mere mortals. Keep up the good work Davy.
  • RavenDB : This will deserve a post of its own to describe just how cool I think this NoSQL-for-.Net-written-by-guess-who is. Not only it makes domain-modeling and application prototyping dirt cheap (no more mapping & OR impedance mismatch bro !), it will also give a run for their money to the existing NoSQL databases out there (I mean, how can you compete with 25 blog posts & 12 releases per week ;) lol). Oh, and if you’re into it, DDD will be most welcome as well (“But Ma, there’s no lazy-loading ! How can I do DDD without lazy-loading & bi-directional navigation properties ?” … “Kiddo, lazy-loading sucks. Big time”).
  • Frameworkitis : It’s a nasty disease, I had it in the past, went through a long detox and now (I think) I’m clean. Unfortunately, I still have a lot of peers that are addicts. Wish they could see the light.
  • “KISS-Mantra” : Repeat 5 times per day “I’m a complexaholic, I will not generify, I will simplicate”. Anybody has a nice wallpaper with a giant yellow Bath duck ? :-)

Ah, I feel lighter now.

Categories: DDD, DotNetHub, ORM, WCF Tags: , ,

Value Object in .Net 4.0 – Take Two

April 5th, 2010 stiiifff 5 comments

I’ve refined a bit my base class for Value Objects in .Net 4.0. Instead of using Tuples, I’ve used anonymous types which have had structural equality since .Net/C# 3.0 (I didn’t know that :-) ).

I’ve also renamed methods to make the intent more clear. Here is what it now looks like (fancy stuff removed for simplicity) :

public abstract class ValueObject<T> : IEquatable<T>
    where T : ValueObject<T>
{
    public delegate object ValueObjectStructuralViewBuilder<TValueObject>(TValueObject valueObject) where TValueObject : T;

    private static readonly IDictionary<Type, ValueObjectStructuralViewBuilder<T>> structuralViewBuilders = new ConcurrentDictionary<Type, ValueObjectStructuralViewBuilder<T>>();

    private static object BuildStructuralView(T valueObject)
    {
        Debug.Assert(valueObject != null);
        Debug.Assert(structuralViewBuilders.ContainsKey(valueObject.GetType()));
        return structuralViewBuilders[valueObject.GetType()](valueObject);
    }

    protected static void DefineStructuralView<TOrDerived>(ValueObjectStructuralViewBuilder<TOrDerived> structuralViewBuilder)
        where TOrDerived : T
    {
        if (structuralViewBuilder == null) throw new ArgumentNullException("structuralViewBuilder");
        var valueObjectType = typeof(TOrDerived);
        structuralViewBuilders[valueObjectType] = va => structuralViewBuilder(va as TOrDerived);
    }

    protected ValueObject()
    {
        var valueObjectType = GetType();
        if (!structuralViewBuilders.ContainsKey(valueObjectType)) throw new InvalidOperationException(string.Format(
            "StructuralViewBuilder not defined for type '{0}'.", valueObjectType.FullName));
    }

    // Method overloads omitted for brevity purpose ...

Creating a Value Object type now reads like this :

public class Leg : ValueObject<Leg>
{
    static Leg()
    {
        DefineStructuralView<Leg>(l => new { l.Location });
    }  

    public Leg(string location)
    {
         Contract.Requires(location != null);
         Location = location;
    }  

    public string Location { get; private set; }
}

Inheritance of Value Object types is now supported, and the added overhead of the base class is a ConcurrentDictionary per Value Object type hierarchy (remember that static members in generic types defines 1 instance per closed generic type).

As always, feedback (good or bad) is more than welcome !

Categories: DDD Tags: ,

Value Object with .Net 4.0

March 22nd, 2010 stiiifff No comments

There’s already been a lot of implementation of generic Value Object base class … but I’ve never been really satisfied with what I’ve seen so far. Most of them uses reflection, or assume that all public properties should be used, or add significant overhead to every instance of the value object type, or just contain too much obscure code for something that should not be so complicated.

So I figured out that I would give it a try :-) Here is my attempt at building a simple to understand, efficient and correct implementation of the generic Value Object base class in C# 4.0:

public delegate IStructuralEquatable StructuralObjectBuilder(T source);

public abstract class ValueObject : IEquatable, IStructuralEquatable
    where TValueObject : ValueObject
{
    private static StructuralObjectBuilder _structuralIdentityBuilder;

    protected static void DefineStructuralIdentity(StructuralObjectBuilder structuralIdentityBuilder)
    {
        Contract.Requires(structuralIdentityBuilder != null);
        _structuralIdentityBuilder = structuralIdentityBuilder;
    }

    protected ValueObject()
    {
        Contract.Requires(_structuralIdentityBuilder != null, string.Format(
            "StructuralIdentityBuilder for type '{0}' was not set in static constructor.",
            GetType().FullName));
    }

    private IStructuralEquatable BuildStructuralIdentity(TValueObject valueObject)
    {
        Contract.Requires(valueObject != null);
        var structuralIdentity = _structuralIdentityBuilder(valueObject);
        Debug.Assert(structuralIdentity != null);
        return structuralIdentity;
    }

    public bool Equals(TValueObject other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return BuildStructuralIdentity(this as TValueObject)
            .Equals(BuildStructuralIdentity(other));
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as TValueObject);
    }

    public override int GetHashCode()
    {
        return BuildStructuralIdentity(this as TValueObject).GetHashCode();
    }

    public override string ToString()
    {
        return BuildStructuralIdentity(this as TValueObject).ToString();
    }

    public static bool operator ==(ValueObject left, TValueObject right)
    {
        if (ReferenceEquals(null, left)) return ReferenceEquals(null, right);
        return left.Equals(right);
    }

    public static bool operator !=(ValueObject left, TValueObject right)
    {
        return !(left == right);
    }

    public bool Equals(object other, IEqualityComparer comparer)
    {
        return BuildStructuralIdentity(this as TValueObject).Equals(other, comparer);
    }

    public int GetHashCode(IEqualityComparer comparer)
    {
        return BuildStructuralIdentity(this as TValueObject).GetHashCode(comparer);
    }
}

I’m leveraging the new IStructuralEquatable of .Net 4.0 that gives us the semantic of structural equality when comparing 2 objects. One of the types that implements this interface by default is the new Tuple generic type, so I’m borrowing it’s equality, GetHashCode & ToString implementations :-)

Eventually, to create a Value Object type, you just have to define its structural identity builder in the static constructor:

public class Leg : ValueObject
{
    static Leg()
    {
        DefineStructuralIdentity(l => new Tuple(l.Location));
    }

    public Leg(string location)
    {
        Contract.Requires(location != null);
        Location = location;
    }

    public string Location { get; private set; }
}

Obviously, if you want to have a somewhat “immutable” value object, you shouldn’t define any publicly accessible setter for your public properties.

Remark: I haven’t implemented support for inheritance of value objects yet. I’ve tried, came up with different solutions but didn’t find any that was satisfactory so … stay tuned. Or, send a patch if you found a good one ;-)

This is a first drop … please send me your comments & suggestions on how to improve it.

Categories: DDD Tags: ,

DDD Immersion Course review

March 8th, 2010 stiiifff No comments

I recently had the chance to follow a 4-day Domain-Driven Design Hands-on immersion course in Paris, with Eric Evans.

It was very inspirational, probably the most interesting course I’ve followed to date. The amount of knowledge contained in the DDD book can be daunting to master, and the course succeeds in clarifying the most complex aspects of DDD as well as delivering the latest evolutions of the approach.

If you are interested in this course, Paul Rayner has written an amazing series of posts about it:

  • Part One – Introduction. What is DDD? Ubiquituous language? a Model?
  • Part Two – Building-Block patterns (eg. Aggregate. Domain Event. Creative Collaboration etc)
  • Part Three – Strategic design – Bounded Context and context mapping.
  • Part Four – Strategic design (continued) – Core Domain
  • Part Five – More on supple design (Specification pattern). Implementation concerns. Discussion.
  • Part Six – Design and agile.
  • Part Seven – Final. Course takeaways and other thoughts.

Happy modeling !

Categories: DDD Tags:

Donate for NHibernate

March 1st, 2010 stiiifff No comments

A donation campaign has started in order to help a great open source tool become even better : NHibernate.

If you are reading those lines, the probability that you or your customers have been using NHibernate, and leveraging its powerful features, is quite high. In a way, you have benefited from Open Source software at its best.

It is therefore a great opportunity for you or your customers (encourage them !) to show support to the people who have spent countless hours crafting a great free tool, and who will, hopefully, continue to do so ;)

Donate !

Categories: ORM Tags:

Mono track @ FOSDEM 2010

February 22nd, 2010 stiiifff 1 comment

2 weeks ago in Brussels, I had the pleasure to attend FOSDEM 2010, regarded as”The best Free Software and Open Source events in Europe“. I’m not ashamed to say that I’ve no experience with Mono so far, but I’m a curious guy, and the event was not far, and even better, free … so I thought, let’s go have a look to see how things are going in the free world ;-)

All in all, I was pleasantly surprised from what I saw. Apart from the fact that the attendees are somewhat different from those you see at the typical Micro$oft conferences, the atmosphere was very nice and you could see a lot of geeks, some younger, some older, having all one common point : the passion about softwares & new technologies.

I mainly followed the Mono track and here are a few things that I think are worth mentioning:

  • The Mono project & Microsoft are not at war (this may be obvious to some but anyway) … they seem to have healthy collaboration (obviously, within the usual legal boundaries that apply). We are far from the clichés of Microsoft, the Evil Empire vs The Good Free World. This is a good thing, diversity brings more creativity, and thus more choice to people.
  • Miguel de Icaza, the charismatic leader of the Mono project, and Vice President of Developer Platform at Novell, was there to make a state of the union speech. Among other things, he praised entrepreneurship (he seems to like Apple and the iPad), talked about the evolution of C# and how good a language it is for most purposes, and granted the audience a few good quotes:

Any developer below the C# bar is just miserable.

No Coca-Cola today ! (Talking about the fact that he would try no to make a marketing talk about Novell’s products)

  • Mono Develop is improving very nicely. I wouldn’t trade Visual Studio for it yet, but it’s interesting to see how those guys are doing their best to provide a free alternative to the Microsoft star IDE.
  • If in the past, Mono was usually lagging far behind and mostly playing catch-up, they are now able to release their free implementation almost at the same time as Microsoft releases major revisions to C#, .Net & Silverlight. Ok, they may not have all the features of the original implementation but this is still an amazing achievement.
  • Mono also has a few unique features that are yet to make an appearance in the .Net world : Ahead of Time compiler & SIMD extensions.
  • Last but not least, MonoTouch allows you to develop for iPhone & iPad in C#.

All in all, those guys are doing a great job, and, for us, typical .Net developers / consultants, looking at the other side of the fence from time to time, is inspirational.

Therefore, DotNetHub would be very happy to welcome speakers that would like to do a session about the Mono project & related technologies. Don’t hesitate to contacts us !

Categories: Mono Tags:

Dependency Injection Inversion

January 19th, 2010 stiiifff No comments

Seems there is still a lot of confusion about what is Inversion of Control, what is Dependency Injection, what are the differences between the two, and how to apply one or the other properly.

Several people have reacted to a controversial post by Uncle Bob on that topic with, among the most vocal ones, Davy. ;-)

IMHO, some of the best posts on the subject that really make a clear distinction between IoC & DI are the following ones:

The whole point of IoC (forget a minute about DI) is to break the dependencies between your classes and design them as  loosely-coupled as possible (to the point that it’s actually useful of course, it’s not an engineering contest).

All the benefits that you get:

  • Dependency Injection
  • Better testability
  • Better maintainability

are just consequences of the good design of your classes (read about SOLID also).

In the end, it’s just good Object-Oriented design, nothing more. And by good, it doesn’t mean complex, it’s actually quite simple once you got it.

Categories: Castle Project, MEF Tags: , ,

2010 Predictions galore

January 8th, 2010 stiiifff No comments

Just did a quick tour on the net about the predictions being made for 2010 in the .Net world … and what is so striking, is that almost everywhere, Silverlight, with its 4th incarnation, is being touted  as one of the stars of the year.

Here a list of random picks:

In 2010, Silverlight 4 will help you build Line of Business (LOB) applications so easily that it’s gonna be laughable. Think about it for a minute … SL allows you to develop web applications that have desktop-like rich feature sets in a cross-platform manner. Also, those web applications can be taken out-of-browser and used as ocasionally-connected applications. Even better, it can transparently leverage your powerful GPU to integrate some crazy-never-seen-before-groundbreaking UI metaphors. Sounds like heaven ? ;-)

Well not yet, because until recently, it was still difficult to access data from a Silverlight application … you had to go through all that boring thinking to design a 2 or 3 tiers architecture, probably passing some DTOs around, mapping, converting or even better, change-tracking, across tiers. But this is soon going to be the past, as RIA Services will simplify all of that. RIA Services is ADO.Net for Silverlight. It lets you access your database directly in your rich UI, query it, change-track it, validate it, bind it, xaml-ize it. Add some LINQ-icing on top and you’ve got some more great magic happening in there.

Sounds like something familiar … desktop applications, almost-direct database access … didn’t we have that in the past ? Wasn’t it a thing called Client-Server ? Damn yeah ! That thing was so simple, I remember now ! Why did we go through all those crazy architecture evolutions, design patterns, … to finally come back to it ! You gotta be wondering ;-)

Anyway, I hope that by now, you’ve noticed that I was a bit ironic about all of this … because I think that you have to be very careful with the latest cool stuff and not just blindly think it’s gonna solve all of your problems. Silverlight is a very fine piece of technology, but it’s easy to fall into some bad practices. RIA Services will be the same kind of beast. It will bring some interesting abstractions, but as with all abstractions, you’ll have some simplifications that will be applied here and there, so beware.

So, let’s get into the game, here are my predictions for 2010:

  • Silverlight will indeed see a broader adoption, and WinForms / WPF desktop applications will continue to slowly decline. There will also most probably be more and more SL projects that, by trying to do so much in a browser, will have performance, scalability & memory problems. Similarly, backend resources will continue to be used inefficiently.
  • Ayende will most probably add a RIA Services-Prof to its profiler suite, helping developers understanding why the heck are so many HTTP requests being sent from the UI to the backend server.
  • The reality depicted by M. Nygard in 2008 will still hold true in 2010 (just replace J2EE by .Net).
Categories: Silverlight, Uncategorized Tags:

Looking back at 2009, and forward to 2010

December 24th, 2009 stiiifff 4 comments

There will probably be thousands of posts like this one but anyway, here I go with my own … I wanna take a little time looking back at 2009 and then set my personal expectations for 2010.

Overall, 2009 was a great year :-)

  • I finally created my own company ! This gives me a certain degree of freedom in choosing the types of project I want to work on, the knowledge I want to acquire and even more opportunities to meet a lot of very talented people.
  • I learned a lot … especially on how to have a more business-centered focus on software development. Thinking about business value, weighting different solutions benefits vs costs, and also, listening & talking more to the business guys.
  • I read a lot, although I still haven’t finished all the books I started. Functional & concurrent programming, domain-specific languages, Scrum, Business/IT Alignment are in my continuous learning bag.
  • I followed a great course with Udi Dahan and it helped me gain some new perspectives on how to rethink about software design in general. Messaging, SOA & DDD are fascinating topics I want to further learn from.
  • Articles & presentations of Eric Evans on DDD and Udi on CQRS had a tremendous impact on my view of software building. We, software developers tend to focus too much on creating cool frameworks or libraries, and solving complex technical problems, while forgetting about our main goal : providing business value. Sometimes, solving a problem from a business point of view is far easier than at a technical level. Also, we tend to be maniac about every line of code we write … but as E. Evans is saying “Precision design are fragile” & “Not all of a system will be well designed“. Focus your efforts on writing good code in parts of the system that provide most of the business value. It is perfectly fine to write not so good code elsewhere (the duck-tape programmer has its role to play!), just make sure you make everything explicit.
  • Finally, with some friends, I created a new community about the .Net platform & the Agile methodologies, DotNetHub. It’s a very exciting project :-)

So, 2009 was so amazing that I’m eagerly awaiting 2010 !

  • I already booked a DDD immersion workshop with E. Evans in Paris, mid-February, and I’m sure it’s gonna be a great course. Maybe others will follow as I find myself learning a lot during those intensive courses.
  • DotNetHub will keep me busy, organizing great conferences with, well-known and well-known-to-be speakers.
  • I absolutely have to finish all the books I started before I buy any new one !
  • I will restart working on my app based on Northwind and demonstrating DDD coupled with NServiceBus. I have to admit, I got a bit side-tracked by DotNetHub and another major personal event (read further lol).
  • Probably learn some new technical stuff like C# 4.0, VS2010/TFS2010, Dublin & some more F# but honestly, that’s less important and most probably easier than the previous stuff (although F# is quite funky). Using your brain and training your critical sense to filter marketing / wrong piece of information / silver bullets is actually the hardest part of our job.

So, that’s about it folks ! This is the list of my expectations for 2010 … but that’s actually all secondary compared to the main challenge I will have to face : becoming a father end of May 2010 ! ;-) Indeed, my wife is pregnant of my first child. I’m really excited about it … now, on top of my to-do list : read the baby books or get killed :-) lol

Merry Christmas & Happy New Year to all !