Skip to main content

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

Posted by mriem on July 31, 2013 at 11:52 AM PDT

What is wrong with the code below?

  public class ExampleBean implement Serializable {

    public List getItems() {
      ArrayList items = new ArrayList();
      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 side effects in a getter are a VERY bad practice