Sunday, April 15, 2012

A Fluent Builder in C#

When it comes to the number of arguments to pass to a function, Uncle Bob is pretty clear. Quoting from Clean Code:

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided when possible. More than three (polyadic) requires very special justification – and then shouldn’t be used anyway.

Still, some objects might have more than 3 attributes or properties and you usually need some way to initialize them via the constructor. Some attribute might not be mandatory, therefore on some occasions you can get by with a few overloads adding more parameters as needed.

Consider the following (contrieved) example from the world of soccer. I have picked a few attributes that encapsulate the concept of a Team.

namespace Soccer
    public enum Color
    public class Team
        string Name { get; set; }
        string NickName { get; set; }
        Color ShirtColor { get; set; }
        string HomeTown { get; set; }
        string Ground { get; set; }
        public Team(
            string name,
            string nickName,
            Color shirtColor,
            string homeTown,
            string ground)
            Name = name;
            NickName = nickName;
            ShirtColor = shirtColor;
            HomeTown = homeTown;
            Ground = ground;

Let’s try initializing one team:

Team team1 = new Team(
    "Manchester United",
    "The Red Devils",
    "Old Trafford");

Read more: Stefano Ricciardi
QR: Inline image 1

Posted via email from Jasper-Net