-1

I have a jsf piece of view as follows:

<h:selectOneMenu value="#{myBean.selectedRoleId}">
    <f:selectItems value="#{myBean.roles}" />
    <a4j:ajax event="change" listener="#{myBean.roleChanged}"
                     render="roleFeatures" />
</h:selectOneMenu>

and the bean itself:

public class MyBean{
    private Role selectedRole;
    private Integer selectedRoleId;
    private List<SelectItem> rolesSelectItems;
    private RoleService roleService;
    //GET,SET

    public List<SelectItem> getRoles() {
        initRoles();

        return rolesSelectItems;
    }

    private void initRoles() {
        roles = new HashMap<Integer, Role>();
        rolesSelectItems = new LinkedList<SelectItem>();
        //Do some DB operations     
    }

    public void setSelectedRoleId(Integer selectedRoleId) {
        selectedRole = roleService.getBy(selectedRoleId); //Here we are getting 
                                    //actual role by its Id from database
        this.selectedRoleId = selectedRoleId;
    }

}

Is it considered OK to perform additional piece of logic in setters? In my particular case I got actual Role-entity from the DB when user selected another Role with selectOneMenu. To me, setter is a method to perform only settings a particular object and not anymore. That's why I'm asking that question.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • @Tiny I heard somewhere that `@PostConstruct` is not a good annotation to use. Should we avoid using it? – St.Antario Apr 14 '15 at 10:27
  • @Tiny BTW, as far as I know the annotaion is only availble since JSF 2.0. But we have still some projects on JSF 1.2. – St.Antario Apr 14 '15 at 10:28
  • If the Role is a JPA entity object, better use @Postload – HJK Apr 14 '15 at 10:29
  • @user3694267 Yes, it is. But we're using Hibernate 3.5 and as far as I know the annotation is not available in that version.... – St.Antario Apr 14 '15 at 10:31

1 Answers1

0

For me is ok to add additional code to a setter. For example if you know that a string can't be empty you can do something like:

public void setMe(String me) {
    if (me == null) {
        this.me = "";
    } else {
        this.me = me;
    }
}

But it is not correct adding a call to a database int the setter. This should be done in a service that calls a dao.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • Well, actually `roleService.getBy` calls Dao method. – St.Antario Apr 14 '15 at 10:58
  • 1
    A fat -1 for not mentioning the right JSF approach for the specific problem OP is *actually* trying to solve, and hereby thus misguiding the OP and future readers looking for a solution to the same problem. – BalusC Apr 14 '15 at 12:03