#65 Field Accessors

brian Tue 18 Apr 2006

I checked in basic support for field accessor methods:

Str x
{
  get { return x }
  set { x = val; }
}

The syntax is similar to C# - a field declaration can be followed by initial assignment, then an optional {} block. The block can have a get and/or set sub-block. Use the field name to access the actual storage location. The implicit local variable "val" is provided in set with the new value. A getter and setter will be automatically generated for you if one is not specified.

All access inside the declaring class is raw field access. All access outside the class is thru the accessors. The accessor methods may be used directly by the declaring class (or anybody):

x()      // access thru getter explicitly
x("foo") // access thru setter explicitly

For the most part this is a compiler only feature - the fcode didn't change other than some additional bitmask flags. What this means is that the fcode can contain duplicate slots. Fields will contain three slots with the same name: field itself, getter method, and setter method. When a Type reflects it will need to handle this case - the Field is what will be looked up by name. The accessor methods may be reflected via the Field.getter() and Field.setter() methods.

I still have a big chunk of work left to finish this feature up:

  • Reflection: Field.getter and Field.setter
  • Reflection: Field.get and Field.set
  • Accessor specific flags and flag merging
  • Test field, getter, setter flags via reflection
  • Protection scope checking
  • Virtual/override checking
  • Test closures inside getters/setters
  • Readonly fields
  • Once methods (special case of field)

Another big issue is should we support fields in mixins? I'm inclined to say yes because it's so damn useful. But I haven't thought thru all the repercussions.

brian Fri 19 May 2006

Does it make sense to allow a field's getter to be of a different protection scope than a set? It seems like really the get MUST be the same protection scope as the field and the set can only narrow the scope.

andy Fri 19 May 2006

Well they are def independent - are you suggesting that the set can never be more open than the getter? Seems a little arbitrary to restrict that - I say its 100% open.

brian Fri 19 May 2006

Why would it ever make sense to declare a field that had a different scope than the getter?

Why would it ever make sense to declare a setter more open than the getter?

andy Fri 19 May 2006

Its a little wierd if you think about the field and the getter as two different objects (which I guess was doing) - when you consider them correctly as a single entity, I think what you suggested does make sense. Actually, yeah - I think it has to be that way.

brian Sun 4 Jun 2006

I checked support for readonly fields which is just a shortcut for declaring that the setter is private:

readonly Int x

is syntatic sugar for:

Int x { private set }

Login or Signup to reply.