Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct an object with a lot of properties?

Tags:

delphi

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?

like image 476
Pieter B Avatar asked Mar 06 '13 15:03

Pieter B


People also ask

How do you create property of objects?

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.

How many object properties does an object have?

Objects have two types of properties: data and accessor properties.

What are the properties of all objects?

Objects have properties that can be observed and described. Physical properties include size, shape, and texture.


1 Answers

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;
like image 150
TLama Avatar answered Oct 28 '22 07:10

TLama