JSF Utility Class

What do you think of the best way to implement JSF 2.0 beans managed methods, such as:

public FacesContext getFacesContext() { return FacesContext.getCurrentInstance(); } public Flash getFlash() { return getFacesContext().getExternalContext().getFlash(); } public void addMessage(String clientId, String message) { FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, message, message); getFacesContext().addMessage(clientId, facesMessage); } 

I think either as an abstract class, or as a regular class with static methods.

My understanding is that the object resulting from the extension of the classes will consume more memory, but most (almost all) of them are the request area, which has the right to garbage collection as soon as the answer is received.

I am interested in the best OO design and minimal taxation for the server. Thanks

+4
source share
2 answers

My understanding is that an object resulting from class expansion will consume more memory

This is not true. Only the state consumes more memory. These methods do not have / use an extra state - which is why you can make them static without worrying about security issues.

And yes, you see that this is really solved in two main ways:

  • Put them in an abstract class that you allow to all your managed beans.

     public class Bean extends BaseBean { public void submit() { addInfoMessage("Submit successful"); } } 
  • Put them in a utility class that you can eventually import using import static (no, do not confuse it with singleton, since the singleton has state, but the utility class does not).

     public class Bean { public void submit() { Jsf.addInfoMessage("Submit successful"); } } 

Both are acceptable, the main difference is only that the abstract class method is best mocked / tested when testing frameworks, it may happen that this is a strict business requirement.

+2
source

I don’t think you should worry too much about the added effect of the superclass on JSF 2.0. In my project, we created an abstract base class that applies to all Backing Beans that act as a controller. The methods are similar to what you added, and include others. Personally, I would go for an abstract base class approach, for example. name it GenericBean or GenericPageCode, and the IS-A relationship will be fine. I suggest that one of the potential drawbacks is that this abstract base class will be part of the framework, and all its implementations will be sensitive to changes in it ... but it should be just fine, since the methods in the base class are unlikely to change often and destroy concrete implementations.

Of course, the alternative is a singleton, somewhere storing these methods or static methods in the Helper class. This is not my personal preference, since you must import a class each time and either get an instance of it or call a method in the class every time. For me, it is preferable to use methods through inheritance.

+2
source

All Articles