I am having a bit of trouble designing a Class. Creating a Customer Class looks straightforward:
TCustomer = Class
private
FIdNumber: String;
FName: String;
procedure SetName(const Value: String);
procedure SetNumber(const Value: String);
public
Property Name : String read FName;
Property IdNumber : String read FIdNumber;
Constructor Create(Number, Name : String);
end;
constructor TCustomer.Create(ANumber, AName: String);
begin
SetName(AName);
SetNumber(ANumber);
end;
MyCustomer := TCustomer.Create('1', 'John Doe');
But well my customer has more properties: where he lives, date of birth etc. etc.
TCustomer = Class
private
{..snip snip..}
public
Property Name : String read FName;
Property IdNumber : String read FIdNumber;
Property Street : String read FStreet;
Property HouseNumber : Integer : read FHouseNumber;
..
..
..
Constructor Create(Number, Name, Street : String; Housenumber : Integer .. .. ..);
end;
As you see I end up with a constructor with a whole lot of arguments. What is a better way to construct a object with a lot of properties?
One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.
Objects have two types of properties: data and accessor properties.
Objects have properties that can be observed and described. Physical properties include size, shape, and texture.
If a certain class needs to have many fields, I would make a constructor with only mandatory parameters and the rest I would keep in writeable properties:
type
TCustomer = class
private
FName: string;
FIdNumber: string;
FStreet: string;
FHouseNumber: Integer;
public
// constructor is empty or just with mandatory parameters
constructor Create;
// properties are writeable
property Name: string read FName write FName;
property IdNumber: string read FIdNumber write FIdNumber;
property Street: string read FStreet write FStreet;
property HouseNumber: Integer read FHouseNumber write FHouseNumber;
end;
This of course depends, if you can expose those properties so to be writable, but the usage looks in my view better than constructor with many parameters:
var
Customer: TCustomer;
begin
Customer := TCustomer.Create;
Customer.Name := 'Name';
Customer.IdNumber := 'ID number';
Customer.Street := 'Street';
Customer.HouseNumber := 12345;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With