Matthew M Dalby

Software Engineering

Working with Context Level Variables

An introduction

The traditional approach towards defining variables provides a lot of focus on limiting variable scope to the arguments passed into a method. Global variables are generally frowned upon as they can cause confusion and unnecessary code complexity. There are some cases however where working with global or ‘context level variables makes sense.

Externalizing environment specific variables such as a database connection and associated credentials are one example. Generating an unique transaction id for a series of operations within a larger overall operation is another prime example.

Imagine a case where an API is called, which in turn calls a series of services, some of which in turn call other APIs in a microservice type scenario. If the total number of calls made at the end of the day was around 50, and all methods needed access to a common variable, then you would essentially be passing references to that variable all over the place.

In this article we will focus on a scenario where we created a transaction id that will be referenced by all methods for the purpose of including the transaction id in all logging statements, so the entries may be correlated for future auditing purposes. We will dive into implementations in both Java and Node in order to demonstrate how the concept can be universally across both stacks.

A Common Approach

For our example, since we are generating a unique id for each request, and this behaviour is consistent across all API calls, we will define this at a filter or middleware layer. The terminology differs by the concept is the same.

We further decouple how transaction id numbers are generated, and how they are obtained across the application by use of dedicated. This provides a great deal of flexibility for potential future changes..

Implementation in Node

As we can see, assigning a transaction id at the middleware layer is fairly straightforward.

1use strict;
An overview of the code generation process
1use strict;
An overview of the code generation process

Implementation in Java

And here is the isolation of the generate/retrieve functionality in Java.

1use strict;
(/src/main/java/com/matthewdalby/example/context_variables/util)

And our filter which intercepts all requests

1use strict;
(/src/main/java/com/matthewdalby/example/context_variables/util)

As you can see the Java approach is a bit more verbose, however the concept is applied in a universal manner. In both tech stacks, there is a concept of request interception, injection into the scope for the current call a unique transaction id, and the abstraction of how the id is generated and referenced via a dedicated module.

Summary