Tuesday, June 05, 2007

Constants to the Extreme

Those good old days of COBOL. Yes, it's that dusty old memory trail. Many things can be learned from those days, including what not to do. Not everything was sunshine and roses.


Sometimes people who really didn't understand the technology were allowed to make technical decisions. Worse still when that person was a project manager. The suggestion brought forth was that in many cases you did not need to use an explicit number for a loop, you could set the limit as a constant, so if it ever changed you would only have to change the value in working storage. The non-technical manager extended this to say that you could only use constants


For example:


    PERFORM VARYING ProvinceNum FROM LT-ONE BY LT-ONE
UNTIL ProvincName(ProvinceNum) = Province OR
ProvinceNum > LT-THIRTEEN
END-PERFORM

You can see that this looks like someone got carried away. In this case there is no need to make '1' a constant as it will always be '1'. The key was actually in LT-THIRTEEN. This should have been called MAX-PROVINCES or something else. This would have made the statement look like this:

    PERFORM VARYING ProvinceNum FROM 1 by 1
UNTIL ProvincName(ProvinceNum) = Province OR
ProvinceNum > MAX-PROVINCES
END-PERFORM

The same thing can be said for Visual Basic, C#, Java and many other languages. Not only does judicious use of constants make the code easier to understand, but it makes it easier to change. By making it LT-THIRTEEN, you couldn't very well change that to a different number, so you would have to change the code, totally defeating the person of making it a constant in the first place.

No comments: