https://github.com/state-machine-systems/dynamic-reference
Dynamically-scoped variables for Java
https://github.com/state-machine-systems/dynamic-reference
Last synced: 6 months ago
JSON representation
Dynamically-scoped variables for Java
- Host: GitHub
- URL: https://github.com/state-machine-systems/dynamic-reference
- Owner: state-machine-systems
- License: apache-2.0
- Created: 2015-04-28T15:21:57.000Z (about 11 years ago)
- Default Branch: master
- Last Pushed: 2015-08-28T08:32:31.000Z (almost 11 years ago)
- Last Synced: 2025-07-13T02:43:04.649Z (12 months ago)
- Language: Java
- Size: 160 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
Dynamically-scoped references offer a more disciplined alternative to global variables. They're a handy feature from
the Lisp family of languages.
In Java, `static` fields are equivalent to global variables, with all the bad stuff that entails. By contrast, you
create a `DynamicReference` with an initial default value, which can be overridden inside a given block
scope. Code inside the block (at any call depth) will automatically use the overridden value. After the block
finishes, the value reverts back.
Here's an example of overriding a reference to `System.out`:
import com.statemachinesystems.util.DynamicReference;
import java.io.*;
...
DynamicReference out = new DynamicReference<>(System.out);
PrintStream log = new PrintStream(new File("out.log"), "UTF-8");
void sayHello() {
out.get().println("Hello World!");
}
...
// write to standard output
sayHello();
...
out.withValue(log, () -> {
// write to the log file
sayHello();
});
This implementation is based on the `DynamicVariable` class from the Scala standard library.
### Getting started
This library is in the Maven Central repo, so just add the following chunk to your pom.xml (or the equivalent for Gradle/SBT/whatever):
com.statemachinesystems
dynamic-reference
1.0
© 2015 State Machine Systems Ltd. [Apache Licence, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)