In one of my projects, I have this following use case -
I have a variable, that I need to pass around in many methods. Business logic and object creation in those methods are dependent on that variable. It can be the case I have object creation inside a constructor of another class. For those, I am also propagating this variable so that nested object creation can use it.
This way method contract is very clear. Anyone can look at the method and readily know that is the information that this method is working with. But this leads to a messy propagation of the variable in many places across the codebase. Depending on the variation of the use case, sometimes it has to be stored as a field in many classes.
Another alternative is to use ThreadLocal. Where this variable state can be kept. It's clean and easier to implement. The application processing unit
is single-threaded, so thread safety is not an issue.
But the problem is, it affects the clarity of the methods that will be using it.
What is the recommended approach in this kind of scenario?
ThreadLocal
variable you're talking about is really a global variable. If the application is single-threaded, then there's not even a reason to put it in aThreadLocal
, you could just make it a static variable. But: Global variables are bad. They cause hard to understand spaghetti code and make your code hard to test. Why does this variable need to be passed everywhere? The fact that you need this is a hint that you should rethink the design.