Forum Stats

  • 3,722,791 Users
  • 2,244,415 Discussions
  • 7,850,094 Comments

Discussions

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Implicit Getters and Setters

I was wondering why Java forces us to bother with the code clutter of explicit getters and setters, when a compiler modification could add them as needed to each class property in compliance with their access modifiers.

For example, we could have something like this:

public class State {
    public int property;
}

public class ExtendedState extends State {
    private int counter = 0;
    public int getProperty() {
        return property + ++counter;
    }
}

public class Client {
    public void doStuff() {
        State state = new State();
        state.setProperty(5);                     // implicit setter
        int stateValue = state.getProperty();     // implicit getter returns stateValue == 5
        State extendedState = new ExtendedState();
        extendedState.setProperty(5);
        stateValue = extendedState.getProperty(); // getter override returns == 6
    }
    
}

I'm thinking that there must be some good reason why this hasn't been implemented by now, but I can't think of one. No modification to the JVM would be required, so previously-compiled bytecode will still work. The set of code that will compile under this new specification is fully contained in the set of code that won't, so no issues exist with compiling legacy code. If someone has put a getter or setter on the class that is named as if it involves a property, but does something unrelated to it, the compiler will respect that and not overwrite what is specified in the code. Since the access modifiers of the getters and setters correspond to the access modifiers of the underlying properties, data encapsulation would be maintained. If for some reason, people object to it, it could even be implemented as an optional feature that is invoked with a compiler switch. There must be something I'm not thinking of here.

I looked into taking this question to the JCP, but it became immediately apparent that I'm not supposed to be wasting their time with half-baked ideas and intermediate-level questions, so I thought I was try here first.

Best Answer

Answers

Sign In or Register to comment.