Modularizing Queries (Groovy)
Modularization (breaking code into loosely coupled, self-contained pieces) is a common practice in software development. It should be used to improve the organization and readability of Deephaven queries in both Python and Groovy. This guide covers best practices for importing Deephaven scripts stored as notebooks into Core+ queries. In Groovy, you can import scripts that belong to a package whose name matches their file location.
In order to import Deephaven notebooks found in the File Explorer, the scripts must meet the following requirements:
- Belong to a package.
- The package name must match its file location. For instance, scripts in the
com.example.compute
package must be located incom/example/compute
.
Note
It's possible for identically named scripts to be available when Git is integrated as a source for notebooks. When this is the case, the script in the filesystem is imported, as it's not under version control.
Copy the following script into a new notebook:
package test.notebook
return "Notebook"
String notebookMethod() {
return "Notebook method"
}
static String notebookStaticMethod() {
return "Notebook static method"
}
class NotebookClass {
final String value = "Notebook class method"
String getValue() {
return value
}
}
static String notebookStaticMethodUsingClass() {
new NotebookClass().getValue()
}
Then, save the notebook as test/notebook/MyNotebook.groovy
. It can then be imported as test.notebook.MyNotebook
. The following example imports test/notebook/MyNotebook.groovy
and calls its methods:
import io.deephaven.engine.context.ExecutionContext
import io.deephaven.engine.util.TableTools
import test.notebook.MyNotebook
ExecutionContext.getContext().getQueryLibrary().importClass(MyNotebook.class)
MyNotebook.main()
println new MyNotebook().run()
println new MyNotebook().notebookMethod()
println MyNotebook.notebookStaticMethod()
println MyNotebook.notebookStaticMethodUsingClass()
testTable = TableTools.emptyTable(1).updateView(
"Test1 = new MyNotebook().run()",
"Test2 = new MyNotebook().notebookMethod()",
"Test3 = MyNotebook.notebookStaticMethod()",
"Test4 = MyNotebook.notebookStaticMethodUsingClass()"
)
Note
Per Groovy rules, you can run the script's top-level statements via main()
or run()
. You can also use its defined methods like a typical Java class.
Git
Importing scripts from an integrated Git repository works the same way as notebooks with one exception: the script package names don't necessarily need to match every directory. For example, if the iris.scripts.repo.<repo>.paths
property is set:
iris.scripts.repo.<repo>.paths=module/deephaven
The package found at module/deephaven/com/example/compute
will be imported as com.example.compute
, leaving out the module.deephaven
prefix:
import com.example.compute