Problem
Shared state is in certain cases a bad thing. I am in a project right now where pretty much all methods perform some sort of state change. I believe that's a problem. On one hand, I can't reuse the methods because depending on the current system state the new system state after the method call will be different. On the other hand, testing is pretty hard or near impossible in this project.
Question
So I was wondering what techniques are there to prevent shared state or to refactor such an application so there are less inter-dependencies.
One way would be to program in a more functional programming way. What other best practices are there and in which situations are they most appropriate?
Code examples would be very much appreciated if they help explaining the technique.
Example
Bad
ModuleA
Public Sub DoSomething
Range("A2").Value = Worksheets("Sheet2").Range(cellReference).Value + 10
End Sub
ModuleB
Global cellReference = "B22"
Better (because no reference to global variable and no hard-coded sheet and cell references)
ModuleA
Public Sub DoSomething(resultCell, sourceSheet, sourceCell)
Range(resultCell).Value = Worksheets(sourceSheet).Range(sourceCell).Value + 10
End Sub
ModuleB
deleted
Explanation
So, I guess the techniques applied here were:
- Remove hard-coded values and pass them in as parameters
- Remove references to global variables and pass them in as parameters
I know, these are basic best practices one should follow anyway. But perhaps there are some specifically helping to prevent shared state. I think Erik Meijer said that if you have shared state there is generally something wrong (I'm not sure whether I quoted him quite correctly).
Environment
By the way, this is an Excel VBA project with tons of legacy code developed by people without a software engineering background. The answers don't have to be geared towards this particular setup, though.