Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit from generated getters and setters in Play! framework

The Play! framework generates getters and setters for each public field of a model class at runtime.

public class Product {

    public String name;
    public Integer price;
}

will be transformed to

public class Product {

    public String name;
    public Integer price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }
}

The manual explains further:

Then when you want to access a property you can just write:

product.name = "My product";
product.price = 58;

Which is translated at load time to:

product.setName("My product");
product.setPrice(58);

... and warns:

You can’t directly use getter and setter methods to access properties if you rely on automatic generation. These methods are generated at runtime. So if you reference them in code you write, the compiler won’t find the methods and will generate an error.

Since I cannot use these getters and setters from outside of the Play! project, I see no benefit in generating them. What is the benefit compared to public fields, refactorings (encapsulate a field and change the callers) of all modern IDEs taken into account?

like image 343
deamon Avatar asked Sep 27 '11 10:09

deamon


1 Answers

Short answer: Beans require them.

Longer: Beans specification requires (amongst other things) getter/setter for each internal field. I'm not 100% sure, but I assume both Hibernate and Groovy templates expect Java Beans (the POJO Beans, not the Java EE one!), thus they'll ask for getters/setters. Play just saves you time doing that, so you don't have to worry with boiler-plate code (unless you want to define your own getter/setter for some reason, which you can do).

like image 188
Pere Villega Avatar answered Oct 20 '22 00:10

Pere Villega