Search code examples
classvariablesancestordescendant

How to declare variables


A colleague of mine and I have been discussing how to declare variables in a function.

Let's say you have a class called TStrings (using Delphi for the sake of explanation) that has at least one abstract method and a descendant class called TStringList which obviously implements the abstract method, but it introduces nothing else you need that is not already implemented in the ancestor, how would you declare a function variable of type TStringList?

Here are two examples. Which is considered better practice and why?

procedure AddElements;
var
  aList: TStringList;
begin
  aList := TStringList.Create;
  try
    aList.Add('Apple');
    aList.Add('Pear');
  finally
    aList.free;
  end;
end;

procedure AddElementsII;
var
  aList: TStrings;
begin
  aList := TStringList.Create;
  try
    aList.Add('Apple');
    aList.Add('Pear');
  finally
    aList.free;
  end;
end;

Solution

  • It is a TStringList, so you should also declare it as TStringList (first example). Everything else could confuse you or others that read the code later.