Shortcut "data" classes?

Posted by    |       Ceylon

In Ceylon, the following class has an initializer with two locals:

class Person(Name n, Address a) {
    Name name = n;
    Address address = a;
    ...
}

The following class has two attributes, making it a typical data class:

class Person(Name n, Address a) {
    shared Name name = n;
    shared Address address = a;
    ...
}

(The shared annotation has the effect of capturing the declarations of name and address.)

There's a problem with the above. I gave the parameters n and a silly names to avoid a name clash with the attributes. Since in Ceylon, the names of parameters matter, this is really a bit of a problem. The language spec currently resolves the problem by saying that class initializer parameters hide attributes with the same name inside the body of the class. So the following code is legal:

class Person(Name name, Address address) {
    shared Name name = name;
    shared Address address = address;
    ...
}

This feels a little ad hoc to me, but it does fix the problem without breaking anything. However, the code above really does look pretty boiler-platey. I mean, it's a good deal better than:

//Equivalent Java code, even without the getters!
class Person {
    public Name name;
    public Address address;

    Person(Name name, Address address) {
        this.name = name;
        this.address = address;
    }

    ...
}

But it still feels like there's room for improvement. What I want to know is whether we should allow the following shortcut in Ceylon:

class Person(shared Name name, shared Address address) {
    ...
}

I mean, a parameter is just a local like any other, why can't we make it shared, just like we can with locals declared in the body of the class?

The only real downside I can see is that things start to get ugly once we start adding more annotations to these attributes:

class Person(doc "the name of the person" 
             shared Name name, 
             doc "the address of the person" 
             shared variable Address address) {
    ...
}

I'm inclined to not have this feature in early releases of the Ceylon compiler, only because I know it's really easy to add in later, once we all get totally bored of writing code like shared Name name = name; over and over again...

What do you think?


Back to top