When it comes to “new” language features in Delphi (which usually have been in Free Pascal for years) I’m always willing to give them a shot. I’m using the for..in loop a lot, and also tend to shorten my code with things like ifthen (the poor mans ? operator, but sadly without any compiler magic). And I also use the with statment a lot, though it doesn’t have the best reputation amongst Delphi coders due to it’s scope problems.
One thing I always liked about FPC where the generics, allowing you do e.g. create TLists with your own types saving you lots of typecasts. And as far as I’m aware generics were included with Delphi 2009, so XE2 allows me to implement them into my code too. So while working on the AI for “Phase 2” I decided to give them a shot and implemented them in a function that generates random data for counter espionage :
[delphi]…
TmpType : TBuildingType;
BuildingTypeList : TList
// Gather available building types
for TmpType in BuildingTypePool.BuildingType do
if Owner.TechnologyTree.IsTechnologyResearched(TmpType.NeededTechID) then
if TmpType.Category = BuildingCatSpecial then
BuildingTypeListSpecial.Add(TmpType)
else
BuildingTypeList.Add(TmpType);
// Generate random fake data
CounterIntelligence.FakeStructure.TurnUpdated := CurrentTurn;
for x := Low(Region.Building) to High(Region.Building) do
for y := Low(Region.Building[x]) to High(Region.Building[x]) do
if Region.Building[x,y].IsSpecial then
CounterIntelligence.FakeStructure.BuildingID[x,y] := BuildingTypeListSpecial[Random(BuildingTypeListSpecial.Count)].ID
else
CounterIntelligence.FakeStructure.BuildingID[x,y] := BuildingTypeList[Random(BuildingTypeList.Count)].ID;
BuildingTypeList.Free;
BuildingTypeListSpecial.Free;
end; …[/delphi]
Usually I’d use dynamic arrays in such a function and adding element after element via SetLength, but with a generic list using my own types the code looks cleaner and I don’t have to care about resizing arrays myself.
So what do you guys think about using generics in Delphi? Do you use them all the time, sometimes or never? I’ve heard the implementation still has it’s share of bugs and generics seem to be pretty slow compared to normal lists or dynamic arrays.