When I use inline declarations, should I prefer const
over var
?
In all online examples, and even in Delphi's own documentation, I see that var
is being used. However, I think that const
often better expresses my intentions, and prevents accidental modifications.
Small example to demonstrate what I mean:
{$APPTYPE CONSOLE}
program VarVsConst;
uses
Spring.Collections,
System.SysUtils;
function UsingVar:string;
begin
var dict := TCollections.CreateDictionary<string, Integer>;
dict.Add ('one', 1);
var pair := dict.ExtractPair('one');
Result := pair.Value.ToString;
end;
function UsingConst:string;
begin
const dict = TCollections.CreateDictionary<string, Integer>;
dict.Add ('one', 1);
const pair = dict.ExtractPair('one');
Result := pair.Value.ToString;
end;
begin
Writeln(UsingVar);
Writeln(UsingConst);
Readln;
end.
So, are there any downsides or dangers to the UsingConst
implementation?
I suppose a downside could be that a program is more easily "hacked" into. It's a static value. Not sure how much more of a downside when you've got a var assignment like str := 'password' but you get the idea, this is more of an "in general" const opinion. In your example I really don't see a difference as far as this goes, but there are people smarter than me who could spot it if there.
I like const, once it's assigned you can't fubar things accidentally. If I'm that worried about a hack I can change things after the fact, closer to release.