Friday coding contemplation

I haven’t really been to roads end with this one, so bear with me if it doesn’t quite make sense.

When coding, I usually like to keep my objects as immutable. But on the other hand I really like the verbose way of initializing objects with Object Initialization. Of course there are ways around this, like named parameters, or just the good old naming variables correctly.


  var p1 = new Person {
    FirstName = "Monkey",
    LastName = "Business",
    Age = 42
  };

  var p2 = new Person(
    firstName: "Monkey", 
    lastName: "Business", 
    age: 42
  );

  var p3 = new Person()
    .SetFirstName("Monkey")
    .SetLastName("Business")
    .SetAge(42);

Where the Set-methods looks like the following.


  public Person SetFirstName(string firstName)
  {
    FirstName = firstName;

    return this;
  }

  public Person SetLastName(string lastName)
  {
    LastName = lastName;

    return this;
  }

  public Person SetAge(int age)
  {
    Age = age;

    return this;
  }

While this doesn’t make the objects immutable at all, it does open some other benefits. From time to time I tend to really dislike properties because they are easy to misuse. I myself don’t have a right or wrong answer, but to me they should be lightweight accessors and not perform a whole slew of stuff. If you are in that position a method might be good.

I guess the gist of this is that there are ways of doing things which we might forget. And while we love our fluent APIs, we are quite crappy at actually creating and using them for ourselves when not served via a library, framework or something. But all we really have to do is return this;.

What’s your flavour?

Tagged , ,