I am reading that the playframework is removing global state that is in older 2.4.x versions.
Can someone explain where the global state currently is and what are the benefits of removing global state?
What is the global state?
There is an object play.api.Play
with the following field:
@volatile private[play] var _currentApp: Application = _
Where is it used?
Whenever you do Play.current
you refer to that single mutable global field. This is used all across the framework to access things such as:
play.api.Play.configuration
takes an implicit appplay.api.libs.concurrent.Execution.defaultContext
calls the internal context, which uses the currently running app to get the actor systemplay.api.libs.concurrent.Akka.system
takes an implicit appplay.api.libs.ws.WS.url
takes an implicit appWhy is that bad?
A number of functions just take an implicit app, so that's not really global state, right? I mean, you could just pass in that app. However where do you get it from? Typically, people would import play.api.Play.current
.
Another example: Let's say you want to develop a component that calls a webservice. What are the dependencies of such a class? The WSClient
. Now if you want to get an instance of that, you need to call play.api.libs.ws.WS.client
and pass in an application. So your pretty little component that logically only relies on a webservice client, now relies on the entire application.
Another big factor and a direct consequence of the previous point is testing. Let's say you want to test your webservice component. In theory, you'd only need to mock (or provide some dummy implementation of) the webservice client. However now that somewhere in your code you're calling play.api.Play.current
, you need to make sure that that field is set at the time it is called. And the easiest way to ensure that is to start the play application. So you're starting an entire application just to test your little component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With