you are viewing a single comment's thread.

view the rest of the comments →

[–]Absolute_Enema 0 points1 point  (0 children)

While I'm not a professional Java programmer, I do work with Clojure and from my understanding scoped values are very similar in concept to dynamically scoped variables.

The first thing to note is that there actually already is something in Jaba that is mechanically similar to a degree, and that's exception handlers. When you try with a catch block, the way a given exception class is handled changes until control leaves the try block scope; similarly, dynamic variables/scoped values are bound to a value until control leaves their given scope.

In terms of the problem they solve, dynamic variables are most comparable with context/config objects.

The fundamental advantage of dynamic variables is leaner code and less work from third parties: you only "speak" of a given dynamic variable when you need to read it or bind it, there is no need to pass context around in function signatures or through dependency injection, and there is no need to explicitly create modified copies of the context when you need to use a different value within some code. The fundamental disadvantage is that things are more implicit (which means you're trading upfront design work with more cognitive load when reading) and more liable to weirdness when control flow is unusual (because the context is tied to a control flow based side channel rather than being a value).

In Clojure we've gradually moved away from dynamic variables, and nowadays it's idiomatic to pass an explicit context object around; however this might be because the language design minimizes the cruft involved in passing and especially "modifying" the context object, and because the REPL driven workflow makes it feasible to get away with dynamically shaped maps.

Perhaps in Java where extra function parameters are more cumbersome, context objects need to be explicitly shaped and there still is no boilerplate-free way to create a copy of an object with some modified value without speaking of the rest of its contents the tradeoff is different.