Property Syntax Revised
Since I wrote the last entry about properties, the comments and Groovy changed my mind about the property syntax:
- I think the accessor method syntax that panzi proposed is much better than my Java-like syntax or the C# syntax.
- If the language uses the 'virtual' keyword for virtual methods, virtual properties (properties without associated member field) can not use 'virtual' as a keyword. Otherwise it would not be possible to override the accessors in a sub-class. But the keyword is not needed anyway, because the new accessor syntax can unambigously define a property. You just need to write one or both accessor methods. For the API documentation only one accessor method must be documented, and it should be documented like a field (and not like a function)
- Groovy has the simple and effective idea that all public field members are properties. This removes the need for the 'property' keyword and also the difference between properties and fields. Just add a regular member, and it is accessed using auto-generated accessor methods, that can be overwritten by you
- There's one drawback when properties are accessed like field-members: you can't control anymore whether you access the field directly, or using the accessor methods. This can only be avoided with a syntax extension, and I think the least painful is the following: a method can access the raw field member of the object class without the accessor methods by prefixng the name with a '@'. It is not allowed to use this kind of access for other instances or classes (thus only '@field' is allowed, but never 'ref.@field').
In order to prevent errors, the accessors must not call themselves and thus the attempt to read the field without '@' would cause a compilation error.
Here is the example class with these changes:
class SubString { private int mEndIndex;It's short. I am not very happy about the '@' thing though./// Documentation! public int beginIndex; /// Documentation! public int length.get() const { return mEndIndex - @beginIndex; } public void length.set(int value) { mEndIndex = value + @beginIndex; }
};