Modern constructor — how does it look?

For sure the way the constructors are written in C++ has to go — starting from naming constructor not by a name of the class, but simply “__construct” (like in PHP) or “init” (I would also like to add ability to return a value, but it is a minor thing as well). The real problem is how to initialize object fields in a constructor — briefly, yet in informative way?

Scala integrated constructor went too far — the code is very concise, true, but at the expense of the readability. Entire body of a class becomes a constructor and this means constructor parameters are leaking directly into all class methods.

C# is much better in this regard, I love its syntax:

new Person()
  {
    FirstName = "Joe",
    LastName = "Doe"
  };

The problem? It is not a constructor really (just the first line is). It is not only the matter of the name though, there are technical implications as well — “FirstName” and “LastName” cannot be readonly properties for example. But the clarity is hard to beat.

So the question for Skila is really this — how to bring C# syntax and make it real constructor? So far I came up only with an idea of macro constructor…

Mark the fields of the class which can be initialized by simple assignment and call constructor as usual — all parameters for marked fields are passed via magical “ini” tuple and initialized in one assignment.

class Foo
  var FirstName <- String("John");
  var LastName <- String;
  var BirthYear Int;

  def init(birthYear Int, $ini)
  do
    this.BirthYear = birthYear;
    this.$ini = $ini;
  end
end

new Foo(1918, FirstName : "Joe",
              LastName : "Doe");

Some of the features of macro constructor:

  • field pseudo-initialization serves as indication of optional argument, i.e. you could omit “FirstName” here when creating “Foo” object; it is not field initilization like in C#
  • when passing arguments via “ini” you have to name all arguments — in other words “ini” expands to a list of forced named parameters, and thanks to that it can always be safely placed as the last (pseudo) parameter,
  • because assignment in constructor is explicit you can decide when to call it.

Is this the best what can be done in 2013? Do you have better ideas?

Tagged , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: