Writing testable and maintainable JBang scripts
development testing scriptingI regularly write scripts to automate various tasks. Over the years, I’ve used a variety of languages to write these scripts. I started off writing scripts in Bash. Then I switched to Python for the more complicated scripts. But over the past year, I’ve been using JBang for scripting. This article describes how I’ve been writing testable and maintainable JBang scripts.
Scripting using JBang
I like the idea of using Java since it’s the language I use for most of my development. It’s also statically typed, which helps me catch errors early. But after a while, however, I felt that single file, self-contained JBang scripts were not enough. In order to properly leverage Java, I needed to be able to write testable and maintainable scripts.
Develop scripts using TDD
Some scripts were complicated, and I wanted to break them up into multiple classes.
I also wanted to develop the scripts using TDD instead of doing the equivalent of testing them in production (note: git revert
is a handy way to undo the effects of a text processing script that goes wrong).
Refactor code from scripts into a shared library
Also, I wanted to minimize code duplication in the scripts by having a library of utility functions. I’ve found a good strategy is to aggressively refactor the scripts to move as much code as possible into a shared library of utility functions.
An example
Here’s a Gradle project that illustrates how I’ve been developing JBang scripts.
The key ideas are as follows:
- Each JBang script is ‘one-liner’ that delegates to a command class
- The command class contains the logic of the script that delegates as much as possible to utility functions
- The utility functions are in a separate Gradle subproject used by multiple scripts
- The command class (and the utility functions) are tested using JUnit 5
- The command class and utility functions are published to Maven local
Need help with accelerating software delivery?
I’m available to help your organization improve agility and competitiveness through better software architecture: training workshops, architecture reviews, etc.