JSF Tip #27 - Do not put code with side effects in a getter method

What is wrong with the code below?

  @Named
  @RequestScoped
  public class ExampleBean implement Serializable {

    public List getItems() {
      ArrayList items = new ArrayList();
      items.add("TEST1");
      items.add("TEST2");
      return items;
    }
  }
        

Remember the getItems method can be called multiple times during lifecycle processing.

While the implementation above works, what if we change one thing?

Lets change items.add("TEST1") to items.add("TEST1" + System.currentTimeInMillis()).

See the problem now? For every call to getItems the actual list will change.

So if you are referring to the list multiple times in your JSF page you will now get different results.

So what options do you have to fix this problem?

  1. Initialize your bean in the constructor
  2. Use a @PostConstruct method

But how do I make changes then?

  1. Use a value change listener method and implement how to do the changes in there.
  2. Use an action method and implement how to do the changes in there.

Hope this makes it clear that having side effects in a getter is VERY bad.

Posted July 31, 2013

Up