Tuesday, 22 May 2007

Global Variable Rant

Taking over someone else's programs is never an easy task. I'm not about to judge the programmer as I was not there for the decisions made, or the time pressures and stress that was going on at the time.

However, I will ask every fledgling and seasoned programmer out there to spare a thought for best practice techniques. Trying to read code where extensive use of global variables are used is well nigh an impossible task.

Instead, create objects and define limits within those objects using such things as Sets (e.g. TMyStatus = (stActive, stInactive, stPaused);) and/or comments which allow another person to know what is happening. Please use variable names that can give some indication as to what its used for. Variable names like glbBoolsghSet02 (I made that one up) tells another programmer nothing.

Good commenting IS needed even in good Delphi code. I'll leave explaining what I mean by good commenting in another blog a little later.

Enjoy life, there's reason in that madness - its just buried a little deeper in some objects.

2 comments:

  1. AnonymousJuly 25, 2007

    I know this post is old but I want to share with you this clever tip I've seen on Java programs. When the need to use global variables arises (and sometimes do), the best you can do to avoid a mess is to implement them inside a Singleton pattern. It's a simple object that can only be instantiated once, the class keeps control of that, and you have one property for each global variable needed.
    Hope this helps,
    Daniel

    ReplyDelete
  2. I have been slowly moving the global variables into an object with definitions and sometimes read/write methods. But this is a very large task with, in some cases global variables numbering into the many hundreds.

    This would be considered "unproductive" work resulting in the applications working no differently - therefore I can only do this when/where I can while making other changes.

    However, your suggestion caused me to do a little research.

    For those who want a Delphi implementation of the Singleton Pattern, take a look at http://www.castle-cadenza.demon.co.uk/single.htm

    Thanks Daniel.
    Steve

    ReplyDelete

Note: only a member of this blog may post a comment.