#5 Field Definitions

brian Wed 7 Dec 2005

Based on our original field discussion, and more thoughts Andy and I had tonight...

There is no distinction between a field versus a property like there is in C#. Every field is always wrapped with a getter and setter method unless it is private. The getter and setter is automatically generated for you, with syntax for specifying your own implementation.

The actual storage location field is always private and only accessed by the declaring class. Everyone outside the class access the field thru the getter and setter. This provides a uniform binary interface for field access.

A simple Fan example:

Int x
protected id := "foo"

Expands to in Java:

private long x;
public long x() { return x; }
public void x(long value) { x = value; }

private String id;
protected String id() { return id; }
protected void id(String value) { id = value; }

The syntax for overriding the getter and setter is similar to C# except you can specify just one or the other if you want to inherit the default implementation:

// override setter to call dirty
x := 0
{
  set { dirty; x = value }
}

// override getter and setter to call check
Str foo
{ 
  get { check; return foo }
  set { check; foo = value }
}

// override scope of setter, but use default implementation
foo := ""
{
  namespace set
}

// convenience for making setter private
readonly Str foo

The only drawback to this approach is a purely computed field would still declare storage space. We could add a mechanism to say don't declare space. But I kind of feel like: so what - it keeps things clean and when the hell do you ever use a computed setter (since any method that takes no args looks like a getter)? Although if allow any method that provides one parameter to use the assignment operator then you could implement the getter and setter methods yourself (although Andy and I are inclined that design).

brian Fri 9 Dec 2005

Based on our conversation today:

Foo bar := new Foo();

Expands into:

private Foo bar = new Foo();
public Foo getBar() { return bar; }
public void setBar(Foo value) { bar = value; }

Note that:

  1. we use Java getter/setter convention
  2. our convention is to specify declaration type for fields rather than just implied typing
  3. we will allow getBar to be access using .bar
  4. we will allow setBar to be used in lhs of .bar =
  5. any method using getX/setX pattern can use 3/4

This gives us a standard elegant way to use .xyz = against methods without creating special cases. Plus it works well when calling against Java libraries or when exposing Fan code to C#/Java code.

Login or Signup to reply.