Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where was global scope in playframework and what are the benefits of it going away?

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?

like image 938
Blankman Avatar asked Nov 08 '22 20:11

Blankman


1 Answers

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 app
  • play.api.libs.concurrent.Execution.defaultContext calls the internal context, which uses the currently running app to get the actor system
  • play.api.libs.concurrent.Akka.system takes an implicit app
  • play.api.libs.ws.WS.url takes an implicit app
  • and many more places..

Why 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.

like image 122
rethab Avatar answered Nov 14 '22 21:11

rethab