A r t i c l e s
Navigation

Note: This site is
a bit older, personal views
may have changed.

M a i n P a g e

D i r e c t o r y

Writable Constants Are Useful


I don't like the name writable constants. They should have been named something else, such as peristant local scope variables. They are not constant! They are variable! They just have local scope and retain their values throughout the lifetime of the program. They are not local memory within the function that gets destroyed when the function ends. So why call them writable constants?

People stopped using writable constants mainly because of the name. They make excellent counters and if they were named something else such as persistant variables, people would have used them more.

I've found many uses for persistant local scope variables. Consider a GUI application that has a main form in it. You only want to initialize some widgets the first time the form is loaded on the user's screen.

(note: however, they are like a global variable and can be considered evil.. too)

See below how to use writable constants (persistent local scope variables).

  procedure TfrmMain.Form1Show(Sender: TObject);
  const
   {J+} // <-- may have to turn this on first
    counter: integer = 0; //writable constant
   {J-}
  begin
    { only initialize the form widgets the first time the form is shown }
    if counter = 0 then inc(counter);
    if counter = 1 then frmMain.InitializedWidgets;
  end;

  procedure TfrmMain.SomeOther;
  begin
    // counter is NOT accessible here, because it is local to above procedure only
  end;

The local scope protects the unit's namespace from being polluted. If we had just used a global counter variable, the name space becomes polluted and variable names start to conflict with each other.

  var
    counter: integer = 0; //global variable
  procedure TfrmMain.Form1Show(Sender: TObject);
  begin
    { only initialize the form widgets the first time the form is shown }
    if counter = 0 then inc(counter);
    if counter = 1 then frmMain.InitializedWidgets;
  end;

  procedure TfrmMain.SomeOther;
  begin
    // counter is accessible here, dangerous, polluted unit namespace    
  end;


About
This site is about programming and other things.
_ _ _