Recently I tried to refurbish the code of a toolbox that I have created in Matlab. I have developed the code many many years ago when I was taking my first steps in programing with matlab and my coding skills were far from good. The main objective, which I thought it would be easy, was to remove all the global variables. Well, in practice I realised that this more difficult than I anticipated.
When I have developed the toolbox, which consists of about 30-40 functions, I thought that it will be much easier to develop my code using global variables. The main reasons for using global variables were:
- Avoid to pass extra variables or parameters from one function to the other
- You don’t have to think really hard how to design your set of function
So, what is happening here is, that in the end you save some time when you develop your code. You create function will less arguments which is time consuming if you call this functions lots of times. You are more relaxed when you develop your code and create a new function. And more or less the above was enough for lazy person like me to justify the use of global variables.
What I realised later is that the second point in the long run has the exact opposite effect! Using global variables without discipline can mess your design information. This can create problems like:
- Difficulty in following the flow of the code
- Difficulty in tracking a logical error in the code
- Difficulty to point the exact point/source of the error
However, removing the global variable of an existing code is not that easy. More or less not only I have to redesign large parts of my code but also I must change my way of thinking. And yes, this is the price I pay for being lazy in the first place!