Adam Bien's Weblog

Thursday Nov 16, 2006

Property Based Access in JPA - is an Emerging Antipattern

Thinking longer about property, vs field based access, I cannot imagine a reasonable use case for the property based annotation. It is much cleaner to hide the internal, also persistent, state and expose only business methods (instead of dumb getters/setters).
So you should use:

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="ID")
    private Long id;

instead of:

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="ID")
    public Long getId(){return this.id;}

The field-based injection clearly separates between the business logic and state and promotes encapsulation.
And remember, Getters/Setters are evil, but sometimes necessary (e.g. if you like to use detached objects as Value Objects).


[This entry is based on / extends my books: Enterprise Architekturen, Leitfaden fuer effiziente Software-Entwicklung and: Java EE 5 Architekturen, Patterns und Idiome]

 Rss

Kommentare:

I actually agree. In fact, as we move more and more towards this end, why have getters and setters when all we really want is just a data structure, meaning, we just need something to pass around in our language/platform. Do we really need to have behaviour in these data objects? Personally, I have been moving towards externalizing all "logic" so that what goes from the front to the back is the equivalent of structs.

Gesendet von Jin Chun am November 17, 2006 at 02:56 PM CET #

There's a functional difference at least for Hibernate (See Page 564 in "Java Persistence with Hibernate"). Hibernate allows to invoke the identifier getter method on a proxied object without hitting the database but only when the annotations are placed on the accessors (whereas the object will be initialized from the database when the annotation is put on the field). So in terms of efficiency it might be better to put it on the accessors.

Gesendet von Stefan Krause am November 16, 2007 at 11:29 AM CET #

I prefer field based access as well. It provides more flexibility than the property-based access and also I can view all the fields together and have a complete understanding of the mappings.

rk
http://www.RentalAndRealEstate.com

Gesendet von rk am February 12, 2008 at 03:28 AM CET #

I beg to differ. Property based annotation allows shielding of the value so only limited relevant functions will be able to access it's value or do changes, so limitting chances of mistake. It's dumb, yes. But it's the extra protection.

Gesendet von HDB For Rent am June 25, 2008 at 06:08 AM CEST #

Senden Sie einen Kommentar:
  • HTML Syntax: Ausgeschaltet
About

About me: www.adam-bien.com
JavaONE 2008 Interview
My Recent Books
Adverts
Search
Links
greenfire.dev.java.net
...the last 150 posts
...the last 10 comments
my.netbeans.org
Visitors
License