Waaah, the Play! framework has so many static methods. Where I go to school, we were told never ever to use any statics, yet Play! uses it like there\'s no tomorrow
The main problem is that static methods only have access to other static methods and fields, which results in 'static cling' whereby the static methods have to rendezvous with the rest of the application (which contains its collaborators) via common static field(s), which leads to inflexibility.
Disclaimer: I don't know much about 'play!'
From a very brief look, I'd say it kind of makes sense: web requests are stateless, so there is no object to receive the request (=the method). Thus, mapping an URI such as "/articles/archive?date=08/01/08&page=2" to a static method called archive()
on, I guess, your application class makes sense.
Play uses static methods only when it makes sense:
You can now use Spring DI within Play, see https://stackoverflow.com/a/16552598/10433. I'm using it and it works fine so far.
If you are an Object Orientated Programming purist, you shouldn't use static
methods/fields, however they can be used safely, and don't have to be a cause for concern IMHO.
Play framework is not a good demonstration of when using statics is appropriate, nor it proves that your teacher was wrong. Play is kind of cheating, solves the issues of statics outside the Java language.
The key problem is that you have to process multiple HTTP requests in parallel, and static fields are "global". So you will need one instance per thread (or even better, one instance per HTTP request) for certain things, yet some of those things are returned by static methods in Play. That works because Play! uses ThreadLocal
-s heavily, and so it solves a problem of statics outside the Java language. But that's not everything. Some say that controller methods are rightfully static. Sure, but in plain Java it would be inconvenient, as then you can't access request-specific data without some kind of prefix, like req.
in req.session
, and then you still have to get req
from somewhere, like as a parameter of the static controller method, which is even more hassle. Yet in Play you can you just directly write session
and like, they are just static fields. That's because Play uses bytecode instrumentation to change all those static field references to something smarter. Again, a solution outside the Java language. Those are not static fields at the end.
So, in general, avoid non-final statics. Play does the magic for you though, so don't afraid of them in this case.