Search code examples
jsfsetterbusiness-logic

Adding additional piece of logic into setters?


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.


Solution

  • 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.