Language question: Do you use variables that are assigned once and never thereafter, making them almost but not quite constants?

Language question: Do you use variables that are assigned once and never thereafter, making them almost but not quite constants?

I have a common pattern in my code where I will have a useful variable in a method, but only set its value once - usually at the top of the code.  For example,

procedure TBar.Foo;
var
  TimeElapsed : DWORD;
begin
  TimeElapsed := GetTickCount - FStart;
  if TimeElapsed > FourHours then...
  else if TimeElapsed > ThreeHours then...
  // etc.
end;

It's a variable because I want to assign it, but I only want to assign it once. What bugs me is that it feels unclean in code - I want it to be a constant, not a variable, ie once set I want the compiler to prevent me writing it again. I could use a function call, but often I don't want to recalculate every time (the above is a simple, low-cost example.)  I just want a write-once, read-many, variable.  Ie a constant I can assign to once at runtime (but not a 'writeable constant', which you can write to any number of times.)

In C++ I'd handle this by using the const keyword:
  const DWORD TimeElapsed = GetTickCount() - FStart;
allowing me to assign it, and to enforce its const-ness, but in Delphi there's no equivalent.

Do you end up with the same almost-constant variable pattern in your code, and does it bother you that you can't enforce it? Would you like a language feature for this? I would.

Comments