Home > Enterprise >  Scala legacy code: how to access input parameters at different points in execution path?
Scala legacy code: how to access input parameters at different points in execution path?

Time:09-17

I am working with a legacy scala codebase, and as is always the case modifying the code is quite difficult without touching different parts.

One of my new requirement in to make several decisions based on some input parameters. Problem is that these decisions are to be made at various points along the execution. So either I encapsulate all those parameters in a case class instance and pass it along. But it means I would have to modify multiple methods signatures, and I want to avoid this approach as much as possible.

Another approach can be to create a global object containing all those input parameters and accessible from different points in the execution. Is it a good approach in Scala?

CodePudding user response:

No, using global mutable variables to pass “hidden” parameters is not a good idea, not in Scala and not in any other programming language. It makes the code hard to understand and modify, because a function's behaviour will now depend on which functions were invoked earlier. And it's extremely fragile, because you might forget setting one of those global parameters before invoking the function, which means that it will use whatever value was stored there before. This is the kind of thing that can appear to work for years, and then break when you modify a completely unrelated part of the program.

I can't stress this enough: do not use global mutable variables, period. The solution is to man up and change those method signatures. Depending on the details, dependency injection may or may not help in your particular case.

  • Related