2009. április 18., szombat

Abbreviating Array Properties


Problem/Question/Abstract:

Wouldn't it be much easier to enter AStringList[Index] instead of AStringList.Strings[Index]? Well you can, and you can add this functionality to your own classes.

Answer:

This may be obvious to some, but it's also something that I haven't come across until now, so I figured it might be useful to someone out there.

For many array properties found in classes in delphi, you can simplify access by abbreviating the call.  This means that you can use the syntax ArrayProperty[Index] as opposed to ArrayProperty.Items[Index].

Either way is appropriate, and there is no right or wrong, however here is what I think.  The advantage to using the abbreviated version make repeated calls easier to look at, especially if there are in one parameter list.  The only disadvantage I can think of is that someone else reading the code might not be able to determine what you are referencing without some thought, or knowledge of the class in question.

Here's an example using a TStringList:

Unabbreviated:

for I := 0 to MyStringList.Count - 1 do
  ShowMessage(MyStringList.Strings[I]);

Abbreviated:

for I := 0 to MyStringList.Count - 1 do
  ShowMessage(MyStringList[I]);

Again, in that example it really doesn't save much, but in my code I have some classes I created and have to repeatedly call different sometimes.  Here's an example of something I might do, and how the abbreviation cleans things up:

for I := 0 to UserList.Count - 1 do
  if AUser.Read(UserList.Items[I].Company, UserList.Items[I].User) then
  begin
    ACompanyStr := UserList.Items[I].Company;
    AUserStr := UserList.Items[I].User;
  end;

Now the code in this example is pretty useless, and some would say why not use a 'with UserList.Items[I] do' statement to clean things up.  However often I might have these nested within other 'with' statments, so the 'with' solution is not available.

Now look at the abbreviated code:

for I := 0 to UserList.Count - 1 do
  if AUser.Read(UserList[I].Company, UserList[I].User) then
  begin
    ACompanyStr := UserList[I].Company;
    AUserStr := UserList[I].User;
  end;

It definetly reduces the amount of code, and I believe it does clean up the appearance.  

What makes this all possible is the use of the 'default' directive with the corresponding array property.  

This can be used for many different items in delphi already including TStringList, TListItem, etc. but there are some items that do not have default array properties and therefore you cannot access in the abbreviated fashion.

If you attempt to access something that does not have the default array property, such as the TListView component (I.E. ListView[I].Caption instead of ListView.Items[I].Caption), you will recieve an error such as "Class does not have default property".

Nincsenek megjegyzések:

Megjegyzés küldése