views:

28

answers:

1

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.

A: 

I really don't know if I have understood clearly, but if I had a problem with lots of shared states, I would use some state machine.

With this, you might be able to find out what code is state dependant and what code is cross...

For example, to develope a workflow (lots of state info, needed to check what to do) this is a good solution, and you have tons of documentation...

Hope it helps!

SoulWanderer
@SoulWanderer: I added an example section to my question to clarify my question. Thanks for the state machine hint.
Lernkurve