Delphi: Record constructor vs factory function

后端 未结 4 1989
再見小時候
再見小時候 2021-02-12 20:25

So what will be the preferred way of initializing records?

With a \'factory function\':

TMyRecord = record
  valueX: integer;
  valueY: integer;
end;

fu         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-02-12 20:58

    In a Delphi project that I created, I used records instead of classes to reduce the amount of overhead on a list. I would have several hundreds of records in a dynamic array so I created two records. The first record was for the item itself. The fields were made private (yes, you can use private/protected with records) and added read-only properties to the public section. An additional constructor was also added to initialize the record in the correct way. This setup allowed me to protect the contents from this record from other developers. The second record was just a wrapper around a dynamic array of the previous record type. The array would be private and I added methods to get, add and delete records in this list. As a result, the whole list is protected against mis-use by other developers and also has a lot less overhead than a regular TList/TObjectList solution.

    Do keep in mind that records aren't classes. You can't inherit constructors and other methods. They have less functionality than true classes in WIN32 environments. In .NET, they're just promoted to classes again. And it's not very useful to use add a constructor when developers can easily modify the contents of each and every field in your record. You should use constructors to protect those fields instead.

提交回复
热议问题