Stateless object (no fields) - reuse or create new - java

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?

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

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.

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.

Related

Should domain model mappers be static?

In many of the projects I have worked on we often have a lot of classes that map content from one domain model to another. For example from a WSDL generated model to a project specific one.
for example
public class FooBarContentMapper {
public static Foo fromWsToDomain(FooType fooType) {
...
}
}
this can also be a non-static method and the service layer can have a mapper object field instead of calling the static method:
public class FooBarContentMapper {
public Foo fromWsToDomain(FooType fooType) {
...
}
}
I find both ways used a lot, but:
is one of the solutions more efficient in any way?
are any of the solutions considered best practice?
"Is one of the solutions more efficient in any way?"
Define "efficient".
If, by "efficient", you're referring to CPU time and memory requirements, then the "instance" approach can never be more efficient than the "static" approach; at best, it can be as efficient as the static approach, and the difference depends on the frequency of object instantiation, read: how many times are you going to instantiate the "instance" approach.
"Are any of the solutions considered best practice?"
No. The "best practice" here is to match your design to your requirements.
If the mapping operation requires maintaining state, such as dependencies on other services/mappers/whatnot, then going with the "instance" approach makes more sense. One thing you don't want to get into is a world where your application's design consists of singletons that depend on each other. Use the "instance" approach, preferably using an auto-wiring facility such as the Spring Framework or CDI.
If the mapping operation requires no state, and you have an extremely high confidence in that it will never require state in the future, then use the "static" approach - unless you already have an auto-wiring facility at hand, in which case, you might as well choose the "instance" approach with auto-wiring and guarantee that, if the mapping operation requires state in the future, you won't have to alter your design much.
There are other things to consider:
Is your code testable. Mappers are used as collaborators so unit testing the object using the mapper should focus on behavior (i.e is the mapper being used when expected) ?
Is the static class used in more than one place and subject to race condition because the transform method takes a mutable object(remember, stateless static classes are still subject to race condition when taking a mutable object that is referenced by two different threads at same time)?
Does the static object actually share its life-cycle with the object using it?
If the answer is yes to any of these, you should consider switching to instance.

Init field after constructor execution

Suppose a Car Validator and many methods that read its attributes to valid them.
Thus, the best way to structure it is to make Car an instance field.
Two ways of making it :
1) make a constructor taking a Car as argument and then call validate().
2) Remove all constructors but rather pass Car to validate method as arguments: validate(Car car).
If we imagine that this validator must continuously validate, let's say 500 cars.
With the 1) method, 500 validator objects must be instanciated ... Even if Garbage collector is doing its job really well, it doesn't seem to be the best practice.
The benefit is that initialization of Car field is made by constructor => so more natural way.
With the 2) method, we avoid the drawback of the 1) but we have to init Car field into the method validate, that means after object construction. Is that considered as a good practice? Indeed, only validate method use Car field and furthermore, there is only validate method that is not private.
Of course, there is a third way to do this for avoiding all doubts => pass Car from validate method toward each private methods...but I find this very ugly...
Which of the three methods should I choose ?
I think the 2nd approach is an antipattern and should be avoided, it resembles the infamous SimpleDateFormat class (it looks like stateless and thread safe, but it's not).
Regarding the other approaches, if you really have many private methods it would be better to use the 1st approach, otherwise you can use the 3rd approach, it doesn't look too ugly for me.
Also note that using the 1st approach "as is" involves more coupling than the 3rd one. In the 3rd case you can decouple clients of validator from its implementation by injecting a preconfigured instance of validator, whereas in the 1st case you need to introduce a factory to achieve the same effect.
Good practice is typically that which avoids drawbacks.
Use the second method. If you're going to create a CarValidator class and call validate(car) on it to check validity on your objects, that seems a very efficient way to do it. I don't understand why you would think that it wouldn't be best practice?
Are you concerned about setting a private Car variable and referring to it throughout the validation process rather than passing an instance around through all the private methods? As long as the validate method is synchronized, this approach wouldn't be a problem.
I would use a fourth approach and check validity of cars as early as possible by injecting a Validator object into the Car constructors. I find that a far smaller drawback than having invalid car instances hanging around and having to check validity (via validity() or via attribute in Validator object) later (i.e. not fail fast) at multiple places.
Update: If you cannot validate Car instances during their construction, e.g. because you're on the client side, I would consider Car instances as tainted values on your server side and use the tainting checker and your method 2 to untaint them.

Good case for Singletons?

I have an application that has several classes used for storing application-wide settings (locations of resources, user settings, and such). Right now these classes are just full of static fields and methods, but I never instantiate them.
Someone suggested I make them Singletons, What's the case for/against?
I consider the Singleton pattern to be the most inappropriately applied design pattern. In ~12 years of software development I'd say I've maybe seen 5 examples that were appropriate.
I worked on a project where we had a system monitoring service that modeled our system with a System class (not to be confused with Java's built-in System class) that contained a list of Subsystems each with a list of Components and so on. The designer made System a Singleton. I asked "Why is this a Singleton?" Answer: "Well, there is only one system." "I know, but, why did you make it a Singleton? Couldn't you just instantiate one instance of a normal class and pass it to the classes that need it?" "It was easier to just call getInstance() everywhere instead of passing it around." "Oh..."
This example is typical: Singletons are often misused as a convenient way to access a single instance of a class, rather than to enforce a unique instance for technical reasons. But this comes at a cost. When a class depends on getInstance(), it is forever bound to the Singleton implementation. This makes it less testable, reusable, and configurable. It violates a basic rule I follow and that probably has a common name in some design principles essay somewhere: classes should not know how to instantiate their dependencies. Why? Because it hardcodes classes together. When a class calls a constructor, it is bound to an implementation. getInstance() is no different. The better alternative is to pass an interface into the class, and something else can do the constructor/getInstance()/factory call. This is where dependency injection frameworks like Spring come in, though they are not necessary (just really nice to have).
So when is it appropriate to use a Singleton? In that rare case where instantiating more than one of something would literally ruin the application. I'm not talking about instantiating two Earths in a solar system app - that's just a bug. I mean where there is some underlying hardware or software resource that will blow up your app if you call/allocate/instantiate it more than once. Even in this case, classes that use the Singleton should not know it is a Singleton. There should be one and only one call to getInstance() that returns an interface that is then passed to constructors/setters of classes that need it. I guess another way of saying it is that you should use a Singleton for its "singleness" and not for its "globally accessibleness".
By the way, on that project I mentioned where System was a Singleton... Well System.getInstance() was laced throughout the code base, along with several other inappropriate Singletons. A year later some new requirements came down: "We are deploying our system to multiple sites and want the system monitoring service to be able to monitor each instance." Each instance... hmmm... getInstance() ain't gonna cut it :-)
Effective Java says:
Singletons typically represent some system component that is intrinsically
unique, such as a video display or file system.
So if your component warrants single instance accross the entire application and it has some state, it makes sense to make it a singleton
In your case, the settings of the application is a good candidate for singleton.
On the other hand, a class can only have static methods if you want to group certain functions together, such as utility classes, examples in jdk are java.util.Arrays java.util.Collections. These have several related methods that act on arrays or collections
Singleton will give you an object reference, that you can use all over your app...
you will use singleton if you want objects and/or polymorphism...
If you don't ever need to instantiate them, I don't see the point of singletons. Well, I should amend that - if these classes cannot be instantiated, then it doesn't make sense to compare them to singletons - the singleton pattern restricts instantiation to one object, and comparing that to something that cannot be instantiated doesn't make sense.
I find my main use of singletons generally involves a class that has static methods that, after maybe preparing an environment, instantiate an instance of themselves. By utilising private constructors and overriding Object.clone() to throw CloneNotSupportedException, no other classes can create a new instance of it, or if they're ever passed an instance of it, they cannot clone it.
I guess I'd say that if your application settings are part of a class that is never instantiated, it's not relevant to say "It should/shouldn't be a singleton."
I think you no need to create signleton class.
just make this class constructor private.
Like Math class in java.
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
//static fields and methods
}
Singletons often show up in situations like you're describing- you have some sort of global data that needs to live in some place, and you'll only ever need one, preferably you want to make sure that you can only have one.
The simplest thing you can do is a static variable:
public class Globals{
public static final int ACONSTANT=1;
This is fine, and ensures that you'll have only one, and you have no instantiation issues. The main downside, of course, is that it's often inconvenient to have your data baked in. It also runs into loading issue if, for example, your string is actually built, by, say, building something from an outside resource (there's also a gotcha with primitives - if your static final is an int, say, classes that depend on it compile it inline, which means that recompiling your constants may not replace the constants in the app - e.g., given public class B{ int i = Globals.ACONSTANT; } changing Globals.ACONSTANT and recompiling only Globals will leave B.i still =1.)
Building your own singleton is the next simplest thing to do, and is often fine (though look up discussions on problems inherent in singleton loading, e.g. double-checked locking).
These sorts of issues are a big reason why many apps are built using Spring, Guice, or some other framework that manages resource loading.
So basically:
Statics
Good: easy to code, code is clear and simple
bad: Not configurable- you've got to recompile to change your values, may not be workable if your global data requires complex initialization
Singletons fix some of this, Dependency Injection frameworks fix and simplify some of the issues involved in singleton loading.
Since your class is holding global settings, a pro for a singleton could be that you have more control about creation of the singleton. You could read a configuration file during object creation.
In other cases if methods are static there would be no benefit like in javas Math class which has only static members.
A more obvious need for singletons is when you implement factories as singletons, because you can interchange different implementations of this factory.
Sometimes what people think belong as Singleton objects really can be private members of a class. Other times they should be unique global variables. Depends on what the design needs them to be.
If there should be one, and exactly one instance of an object: use a Singleton. By that, I mean if the program should HALT if there's more than one object. A good example is if you're designing a video game that only supports rendering to a single output device, ever. Trying to opening the same device again (shame on you for hardcoding!) would be forbidden. IMHO a case like that often means you shouldn't be using classes in the first place. Even C allows you to trivially encapsulating such a problem without the complexity of making a Singleton class, and still maintain the elements of OO that apply to a singleton. When you're stuck in a language like Java/C# , the singleton pattern is what you've got to work with, unless purely static members will do the trick on their own. You can still simulate the other way through those.
If it's merely a case of interfacing objects, you probably should think more object oriented. Here's another example: let's say our game engines rendering code needs to interface resource and input managers, so it can do it's job. You could make those singletons and do sth like ResourceManager.getInstance().getResource(name). Or you could create an application class (e.g. GameEngine) that has ResourceManager and InputManager as private members. Then have the GameEngine pass these as necessary to methods of the rendering code. Such as r.render(resourcemanager);.
For singletons—can easily be accessed from anywhere, it's like a global variable, but there can only be one copy of it.
Against singletons—many uses of singletons can be solved by encapsulating it within in a parent object and passing a member object to another member objects methods.
Sometimes just using a stupid global variable is the right thing. Like using GOTO or a compounded (and/or) conditional statement instead of writing the same error handling code N times with copy and paste.
Code smarter, not harder.
You should use singletons for modularization.
Imagine the following entities in singleton:
Printer prt;
HTTPInfo httpInfo;
PageConfig pgCfg;
ConnectionPool cxPool;
Case 1.
Imagine if you did not do that, but a single class to hold all the static fields/methods.
Then you would have one big pool of static to deal with.
Case 2.
In your current case, you did segregate them into their appropriate classes but as static references. Then there would be too much noise, because every static property is now available to you. If you do not need the information, especially when there is a lot of static information, then you should restrict a current scope of the code from seeing unneeded information.
Prevention of data clutter helps in maintenance and ensure dependencies are restricted. Somehow having a sense of what is or is not available to me at my current scope of coding helps me code more effectively.
Case 3 Resource identity.
Singletons allow easy up-scaling of resources. Let us say you now have a single database to deal with and therefore, you place all its settings as static in the MyConnection class. What if a time came when you are required to connect to more than one database? If you had coded the connection info as a singleton, the code enhancement would comparative much simpler.
Case 4 Inheritance.
Singleton classes allow themselves to be extended. If you had a class of resources, they can share common code. Let's say you have a class BasicPrinter which is instantiable as singleton. Then you have a LaserPrinter which extends BasicPrinter.
If you had used static means, then your code would break because you would not be able to access BasicPrinter.isAlive as LaserPrinter.isAlive. Then your single piece of code would not be able to manage different types of printers, unless you place redundant code.
If you are coding in Java, you could still instantiate a totally static content class and use the instance reference to access its static properties. If someone should do that, why not just make that a singleton?
Of course, extending singleton classes have their issues beyond this discussion but there are simple ways to mitigate those issues.
Case 5 Avoid information grandstanding.
There are so few pieces of info that needs to be made globally available like the largest and smallest integers. Why should Printer.isAlive be allowed to make a grandstand? Only a very restricted set of information should be allowed to make a grandstand.
There is a saying: Think globally, act locally. Equivalently, a programmer should use singletons to think globally but act locally.
Effective Java says:
Singletons typically represent some system component that is intrinsically
unique, such as a video display or file system.
So if your component warrants single instance across the entire application and it has some state, it makes sense to make it a singleton.
(The above nakedly borrowed from naikus)
In many cases the above situation can be handled by a 'utility class' in which all the methods are static. But sometimes a Singleton is still preferred.
The main reason for advocating a Singleton over a Static Utility Class is when there is a non-negligible cost involved in setting it up. For example if your class represents the file system, it will take some initialization, which can be put in the constructor of a Singleton but for a Static Utility Class will have to be called in the Static Initializer. If some executions of your app might never access the file system then with a Static Utility Class you have still paid the cost of initializing it , even though you don't need it. With a Singleton if you never need to instantiate it you never call the initialization code.
Having said all that, Singleton is almost certainly the most-overused design pattern.

When NOT to use the static keyword in Java?

When is it considered poor practice to use the static keyword in Java on method signatures? If a method performs a function based upon some arguments, and does not require access to fields that are not static, then wouldn't you always want these types of methods to be static?
Two of the greatest evils you will ever encounter in large-scale Java applications are
Static methods, except those that are pure functions*
Mutable static fields
These ruin the modularity, extensibility and testability of your code to a degree that I realize I cannot possibly hope to convince you of in this limited time and space.
*A "pure function" is any method which does not modify any state and whose result depends on nothing but the parameters provided to it. So, for example, any function that performs I/O (directly or indirectly) is not a pure function, but Math.sqrt(), of course, is.
More blahblah about pure functions (self-link) and why you want to stick to them.
I strongly encourage you to favor the "dependency injection" style of programming, possibly supported by a framework such as Spring or Guice (disclaimer: I am co-author of the latter). If you do this right, you will essentially never need mutable static state or non-pure static methods.
One reason why you may not want it to be static is to allow it to be overridden in a subclass. In other words, the behaviour may not depend on the data within the object, but on the exact type of the object. For example, you might have a general collection type, with an isReadOnly property which would return false in always-mutable collections, true in always-immutable collections, and depend on instance variables in others.
However, this is quite rare in my experience - and should usually be explicitly specified for clarity. Normally I'd make a method which doesn't depend on any object state static.
In general, I prefer instance methods for the following reasons:
static methods make testing hard because they can't be replaced,
static methods are more procedural oriented.
In my opinion, static methods are OK for utility classes (like StringUtils) but I prefer to avoid using them as much as possible.
What you say is sort of true, but what happens when you want to override the behavior of that method in a derived class? If it's static, you can't do that.
As an example, consider the following DAO type class:
class CustomerDAO {
public void CreateCustomer( Connection dbConn, Customer c ) {
// Some implementation, created a prepared statement, inserts the customer record.
}
public Customer GetCustomerByID( Connection dbConn, int customerId ) {
// Implementation
}
}
Now, none of those methods require any "state". Everything they need is passed as parameters. So they COULD easily be static. Now the requirement comes along that you need to support a different database (lets say Oracle)
Since those methods are not static, you could just create a new DAO class:
class OracleCustomerDAO : CustomerDAO {
public void CreateCustomer( Connection dbConn, Customer c ) {
// Oracle specific implementation here.
}
public Customer GetCustomerByID( Connection dbConn, int customerId ) {
// Oracle specific implementation here.
}
}
This new class could now be used in place of the old one. If you are using dependancy injection, it might not even require a code change at all.
But if we had made those methods static, that would make things much more complicated as we can't simply override the static methods in a new class.
Static methods are usually written for two purposes. The first purpose is to have some sort of global utility method, similar to the sort of functionality found in java.util.Collections. These static methods are generally harmless. The second purpose is to control object instantiation and limit access to resources (such as database connections) via various design patterns such as singletons and factories. These can, if poorly implemented, result in problems.
For me, there are two downsides to using static methods:
They make code less modular and harder to test / extend. Most answers already addressed this so I won't go into it any more.
Static methods tend to result in some form of global state, which is frequently the cause of insidious bugs. This can occur in poorly written code that is written for the second purpose described above. Let me elaborate.
For example, consider a project that requires logging certain events to a database, and relies on the database connection for other state as well. Assume that normally, the database connection is initialized first, and then the logging framework is configured to write certain log events to the database. Now assume that the developers decide to move from a hand-written database framework to an existing database framework, such as hibernate.
However, this framework is likely to have its own logging configuration - and if it happens to be using the same logging framework as yours, then there is a good chance there will be various conflicts between the configurations. Suddenly, switching to a different database framework results in errors and failures in different parts of the system that are seemingly unrelated. The reason such failures can happen is because the logging configuration maintains global state accessed via static methods and variables, and various configuration properties can be overridden by different parts of the system.
To get away from these problems, developers should avoid storing any state via static methods and variables. Instead, they should build clean APIs that let the users manage and isolate state as needed. BerkeleyDB is a good example here, encapsulating state via an Environment object instead of via static calls.
That's right. Indeed, you have to contort what might otherwise be a reasonable design (to have some functions not associated with a class) into Java terms. That's why you see catch-all classes such as FredsSwingUtils and YetAnotherIOUtils.
when you want to use a class member independently of any object of that class,it should be declared static.
If it is declared static it can be accessed without an existing instance of an object of the class.
A static member is shared by all objects of that specific class.
An additional annoyance about static methods: there is no easy way to pass a reference to such a function around without creating a wrapper class around it. E.g. - something like:
FunctorInterface f = new FunctorInterface() { public int calc( int x) { return MyClass.calc( x); } };
I hate this kind of java make-work. Maybe a later version of java will get delegates or a similar function pointer / procedural type mechanism?
A minor gripe, but one more thing to not like about gratuitous static functions, er, methods.
Two questions here
1) A static method that creates objects stays loaded in memory when it is accessed the first time? Isnt this (remaining loaded in memory) a drawback?
2) One of the advantages of using Java is its garbage collection feature - arent we ignoring this when we use static methods?

Share static singletons through EJB's

I'm trying to create a cache in a webservice. For this I've created a new Stateless Bean to provide this cache to other Stateless beans. This cache is simply a static ConcurrentMap where MyObject is a POJO.
The problem is that it seems as there are different cache objects. One for the client beans, and another locally.
-CacheService
-CacheServiceBean
-getMyObject()
-insertMyObject(MyObject)
-size()
-SomeOtherBean
cache = jndiLookup(CacheService)
cache.insertMyObject(x)
cache.size() -> 1
After this assignment, if I call cache.size from inside the CacheServiceBean, I get 0.
Is it even possible to share static singletons through beans? Finally I decided to use a database table, but I'm still thinking about this.
Thanks for your responses.
As far as I remember you cant be certain that the stateless bean is global enough for you to keep data in static fields. There exist several caching frameworks that would help you with this. Maybe memcache?
EDIT:
http://java.sun.com/blueprints/qanda/ejb_tier/restrictions.html#static_fields says:
Nonfinal static class fields are
disallowed in EJBs because such fields
make an enterprise bean difficult or
impossible to distribute
On the surface, this seems like a contradiction in terms, as a cache is almost certainly something I would not consider stateless, at least in the general sense.
#Stateless
public class CacheSessionBean implements CacheSessionLocal {
private static Map<String, Object> cacheMap = new HashMap<String, Object>();
public Object getCache(String key) {
return cacheMap.get(key);
}
public void putCache(String key, Object o) {
cacheMap.put(key, o);
}
}
The caveats regarding distribution of EJBs in a cluster apply to static variables. However, if you're not clustering, they pretty much don't apply to you, so statics are "okey dokey" at this level.
You WILL have synchronization issues.
One way to mitigate that is to configure your container to only create and pool a single instance of the CacheSession bean, then the container will manage that synchronization for you.
You could also manage the synchronization yourself, but you shouldn't do that at the EJB method level, rather you would likely be better having a synchronized Cache object (vs, say, a generic HashMap).
But the key take away is at this point, static variables are simply static variables.
In theory, you will need to be cognizant of the container lifecycle for your Session Bean (as it can potentially release all instances and thereby the actual bean class could be eligible for GC, thus potentially losing any static data). However, in practice, if the service is popular this is unlikely to happen. But, FYI it COULD happen.
When using stateless beans, you have no control of how many instances of them you have (that's up to your app server to take care of). You could have gotten the output from another bean than the one you looked up from your client. Did you print that in your log? In that case, you maybe should've seen more than one output. The point is that you can't know which instance you get when you look up a stateless bean via jndi (you just get one).
And, you don't have state, so I don't know if this is the best choice for a cache.
By static singleton i suppose you mean a singleton object?
Yes, it shouldn't be a problem to access a singleton through many beans. But remember the concurrency problems you'll probably get. The app server (beans in general) abstracts a lot from you.
I know this post was a while ago but there appears to be a new Singleton Bean that will meet the needs of a cache the original question was aiming at:
http://download.oracle.com/javaee/6/tutorial/doc/gipjg.html
Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application, as opposed to a pool of stateless session beans, any of which may respond to a client request. Like stateless session beans, singleton session beans can implement web service endpoints.
I've tried creating one and referencing it wo issues from a WebService/Stateless bean. worked as advertised.

Categories