17 März 2010

How JavaBean Properties Should Look Like

During a discussion about JavaBean properties in JSF managed beans and entity classes I had an idea for simplify the usage of properties. Because specially in managed beans the getter and setter are annoying and make the code hard to read.

In my opinion the C# way is straight forward:

public class TimePeriod {
    private double hours;

    public double Hours {
        get { return hours; }
        set { hours = value; }
    }
}

But for a simple case like this the C# way is still to complicated.
So why not use annotations and a new modifier called property. For example

public class TimePeriod {
@Get @Set
    property double hours;
}

With the annotations one defines if a property is read-write, write-only or read-only. The new keyword "property" defines how to access the property.I like the possibility in C# to use = operator for getting and setting the properties value. So "property" indicates that one can use = to access the value.

And if you don't like the default behavior you could still override the get and set method for the property.

Kommentare:

Stefan hat gesagt…

Project Lombok does this for you: http://projectlombok.org/features/GetterSetter.html

Simon Martinelli hat gesagt…

Thanks a lot for your comment!
Didn't know about Project Lombok. But it still does not allow to access properties with = operator.
This needs a Java compiler enhancement.

Jonas Bandi hat gesagt…

As you you are pretty obviously flirting with C# lately, let me tell you about another beautiful feature of C# 3.0:

Automatic Properties:

public double Hours {get; set;}


The C# compiler generates the backing field transparently...

kneipentreff hat gesagt…

Use Scala instead ;)
There you only have to define getters/setters if you want to change the standard behavior - which doesn't happen that often as i think.
E.g. a Scala JPA Entity looks like this:

@Entity
class Book {
@Id @GeneratedValue
var id: Long = _
@Column(nullable = false)
var title: String = _
var price: Float = _
@Column(length = 2000)
var description: String = _
}

Nice, isn't it? ;)