Reputation: 153
in my Seam webapp there is a service returning generators for document generation. These objects are without state (no fields), just methods. Is there anything wrong if there is only one instance of each generator inside the service and each request will return the same instance? Or should I always create and return a new instance?
Upvotes: 0
Views: 1139
Reputation: 26856
If the objects have absolutely no state then there is no problem with reusing them. However if they have absolutely no state why not make all the methods static and never create one at all?
EDIT:If this class is a means to pass functionality into a method, then I agree using static methods will not work. In that case then, all else being equal, I would recommend creating a new object purely to indicate to any readers that nothing is preserved between uses. However this is a weak preference, and if there is any other reason to reuse objects, go for it.
Upvotes: 0
Reputation: 13164
Don't know about Seam but it is something like an EJB underneath, isnt' it? In the EJB world there were stateless ejbs for exactly this case: (re)using objects without state.
So if that's possible with Seam and if those objects don't have state, make them kind of stateless beans. They can be then reused safely.
Re: static methods - that might work but depending on the design used at times you can't have static methods but need object instances, like where you want a certain creation flexibility by using factories.
Upvotes: 1
Reputation: 120306
As long as you're sure there's no state being preserved, I don't see a reason why you'd need to re-create it every time.
It'd be similar behavior to a singleton-scoped bean in Spring
Upvotes: 1