Property Accessors - a short introduction

As I stated yesterday I started the discussion about adding Property Accessors to Java. Today I want to show some more about my thoughts.

There are at least three questions?

  • What are Property Accessors?
  • Why Java needs them?
  • What could they look like?

What are Property Accessors?

So starting with the first question “What are Property Accessors?” we'll begin with a quite easy explanation:
At first Property Accessors are a bit of syntactic sugar to avoid writing Getters and Setters manually.
As the second point they bring us a bit more in the direction of the “Uniform Access Principle” to Java. The UAP was defined by Bertrand Meyer and describes that there is no difference between access to members, attributes or methods. There is a quite nice Wikipedia article [1] describing the main aspects of what the UAP looks like.
And last but not least it can give legacy code a chance to be made safer without access to the accessing codebase, I'll show later what this means.

Now let's see a basic pseudocode example of the UAP in work:

class Egg {
  property int color
}

What we see is a really simple class called Egg defining a property color of type int.
According to the UAP we can read / write that property the same way as a field but even as a method:

Egg egg = new Egg
egg.color = 0xFF00FF
print egg.color
egg.color( 0x0000FF )
print egg.color()

Both ways are totally equivalent and exchangeable. So you see no difference in field or method access.

Adding the UAP in Java would give you a third possibility – the JavaBeans standard to be backwards compatible with existing libraries not capable of accessing properties.

Egg egg = new Egg
egg.setColor( 0x00FFFF )
print egg.getColor()

I guess that should work as a short introduction in what Property Accessors mean to me.

Why Java needs them?

This brings us to the next question “Why Java needs them?”.

That one is a bit hard to answer since I guess there will be multiple reasons for different kinds of persons.

The first reason we already know: I'm pretty sure nobody would deny that the UAP is a good pattern to write expressive code.

The second reason I had mentioned earlier, too, legacy codebase that should be made stronger against attacks or mistakes. So let's have a deeper look into what this means.

Imagine a world where there is legacy code, I know this does not exists but still think about it, and the legacy codebase is ugly and using “patterns” like direct fieldaccess. Isn't that an unlikely thought but to make it even more worse: When the field was created the creator thought about it to be in range 0 to 100 but as “speed” was important he decided to dismiss safety for speed and denied to use encapsulation. The codebase was made public and a lot of other people (even external companies) made use of this field.
Some day a bug was filed describing the internal behavior of the surrounding class was wrong. After hours of analyzing the code the only possibility could be: someone sets the field to a value outside of the legal range.

How can we prevent such a problem with a lot of adopters out there?

  • We test the range right before every use of the fields value
  • We encapsulate it, providing a Getter and Setter and break backward compatibility.

In most cases the second step is not a real option (maybe with changing the major version) and the first option prevents the problem at the wrong position. It already happened that the field has a wrong value but you'll never find out who made it a problem.

Using Property Accessors you make the field a property and override the standard Setter using a checking variant. In this case the access seems to be the same as before but you feature the additional behavior of a Setter.

And that leads us to the third question “What could they look like?”

What could they look like?

Before I go on I'll just want to mention that the following examples are just drafts and the syntax is subject of discussion (especially for array index accessors which I do not really like that way they currently noted).

So let's start with our Egg as an example similar to yesterdays post on what properties will be made to by the compiler.

public Class Egg {
  property int color;
}

The compiler would now infer the accessors right to what I described above:

public Class Egg {
  private int color;

  public void color(int color) { this.color = color; }
  public int color() { return this.color; }
  public void setColor(int color) -> Egg::color;
  public int getColor() -> Egg::color;
}

So the compiler generates the missing methods so that old code could use it as before.

To come back to our earlier problem the old “public field” we could change public to property and override the standard Setter like this:

public Class Egg {
  property int color {
    (value) -> {
      if (value < 0 || value > 100)
        throw new IllegalArgumentException(“value out of range”);
      this.color = value;
    }
  }
}

This example uses a Java 8 Lambda syntax to define a new Setter that checks the range of the field. Combined with the UAP we can use it like the fieldaccess before:

Egg egg = new Egg();
egg.color = 80;  // This one will work as expected
egg.color = 101; // This one throws an exception

But this is not the only good thing Property Accessors could give us, there are plenty of options out there.
So had you ever been annoyed of copying arrays to prevent unexpected external changes?

public class ArrayStore {
  private final int[] store;

  public ArrayStore(int[] store) {
    this.store = Arrays.copyOf(store);
  }

  public int[] getStore() { return Arrays.copyOf(store); }
}

What if we could make the returned array some kind of “write-protected”?

public class ArrayStore {
  property final int[] store {
    (index, value) -> {
      throw new IllegalAccessViolationException(“not allowed”);
    }
  }

  public ArrayStore(int[] store) {
    this.store = Arrays.copyOf(store);
  }
}

This would prevent external code from altering the returned array but gives you full access internally of the declaring class. Also you could add an access check using SecurityManager or whatever you want to.

As mentioned before, there are plenty of options on how to use Property Accessors.

For now this should be a good overview of the vision behind the Property Accessor proposal and I'll be glad to answer any of your questions or see you joining the discussion on java.net [2].

The next steps would be to define a clear document with a lot more examples and to bring the idea to the form of an JSR or JEP and possibly making some prototype.
For this step I'm searching for highly engaged people loving this idea and want to help moving it forward into a possible candidate for a language addition of Java.

So if you want to help or maybe already taking place in the definition of a JSR / JEP and like the idea it would be great to contact me at G+ [3] or by mail [4].

Links
[1] http://en.wikipedia.org/wiki/Uniform_access_principle
[2] http://www.java.net/forum/topic/jcp/general-jsr-discussion/properties-proposal
[3] https://plus.google.com/u/0/114622570438626215811
[4] noctarius at apache org