Archive

Posts Tagged ‘NET 4.0’

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

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

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 !

MEF Preview 5 – Recomposition, POCO & Custom Type Systems

April 28th, 2009 stiiifff 3 comments

Go & take the time to read those posts about the latest drop (preview 5) of MEF (Managed Extensibility Framework):

All of this will come for free as part of .Net 4.0 … isn’t that cool or what? :)

Categories: MEF Tags: , , ,

Future of programming languages

March 17th, 2009 stiiifff 2 comments

Very interesting presentation by Anders Hejlsberg.

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

C# 4.0 Goodies

October 28th, 2008 stiiifff No comments

Quick description of the goodies that we will have in C# 4.0 :)

The Future of C#

Categories: Languages Tags: