Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Great Idea: Property Annotations alternative to getter/setters

807569May 26 2006 — edited May 27 2006
Currently, a huge amount of Java objects use property fields with getter/setter accessors:
class MyClass
{
	protected int xyz;

	public int getXyz() {
		return xyz;
	}

	public int setXyz(int xyz) {
		this.xyz = xyz;
	}
}
.NET uses a slightly simpler syntax which internally generates getter/setter methods:
class MyClass
{
	protected int xyz;

	public int Xyz {
		get {
			return xyz;
		}
		set {
			xyz = value;
		}
	}
}
Most of the time (90%+), the getters and setters just set/return. Of course, there are times where it's necessary to implement additional logic without changing the interface presented to other classes. However, there are lots of cases where there is huge amounts of trivial getter/setter code. Also, it takes effort to maintain the getters/setters, when fields are added, deleted, or renamed.

Wouldn't it be much nicer to have trivial getters/setters implied via annotations? Instead of the above examples, do:
class MyClass
{
	// defaults to providing both getter and setter.
	@PublicProperty
	protected int xyz;
}
You could have variants for protected access, private access, and parameters for getter only or setter only. And, you would continue to use the traditional syntax when you want to do non-trivial getter/setter logic.

The big advantage is that this syntax would be much easier to maintain. Much less code to scroll through. Much easier to rename fields. Easier to delete fields. Easier to add new fields without relying on IDE "generate getter/setter" features.

What does everyone think?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 24 2006
Added on May 26 2006
4 comments
322 views