I am still new to Ada and not very proficient in the way object orientation is handled in Ada. :(
I would like to know if it is possible to implement a builder like pattern in Ada? This pattern is quite common in the Java programming language.
A simple example: Let's say I want to model a person object. A person has the following attributes:
I could implement four (overloaded) Create
functions to cover all possible combinations:
declare
Person_1 : Person;
Person_2 : Person;
Person_3 : Person;
Person_4 : Person;
begin
Person_1 := Create(First_Name => "John",
Last_Name => "Doe",
Date_Of_Birth => "1990-02-27");
Person_2 := Create(First_Name => "John",
Middle_Name => "Michael",
Last_Name => "Doe",
Date_Of_Birth => "1990-02-27");
Person_3 := Create(First_Name => "John",
Last_Name => "Doe",
Date_Of_Birth => "1990-02-27",
Place_Of_Birth => "New York");
Person_4 := Create(First_Name => "John",
Middle_Name => "Michael",
Last_Name => "Doe",
Date_Of_Birth => "1990-02-27",
Place_Of_Birth => "New York");
end;
Builder pattern like (don't know if this is possible in Ada):
declare
Person_1 : Person;
Person_2 : Person;
Person_3 : Person;
Person_4 : Person;
begin
Person_1 := Person.Builder.First_Name("John")
.Last_Name("Doe")
.Date_Of_Birth("1990-02-27")
.Build();
Person_2 := Person.Builder.First_Name("John")
.Middle_Name("Michael")
.Last_Name("Doe")
.Date_Of_Birth("1990-02-27")
.Build();
Person_3 := Person.Builder.First_Name("John")
.Last_Name("Doe")
.Date_Of_Birth("1990-02-27")
.Place_Of_Birth("New York")
.Build();
Person_4 := Person.Builder.First_Name("John")
.Middle_Name("Michael")
.Last_Name("Doe")
.Date_Of_Birth("1990-02-27")
.Place_Of_Birth("New York")
.Build();
end;
First question: How could this example be implemented in Ada?
The Build
function could check (at runtime) if all required attributes where initialized by the belonging functions.
Second question: Could this check be delegated (in a magic way) to the compiler so the following example would not compile?
declare
Person : Person;
begin
-- Last_Name function not called
Person := Person.Builder.First_Name("John")
.Date_Of_Birth("1990-02-27")
.Build();
end;
One Ada way of supporting the problem as stated would be to use default values for the parameters whose values aren’t required:
function Create (First_Name : String;
Middle_Name : String := "";
Last_Name : String;
Date_Of_Birth : String;
Place_Of_Birth : String := "")
return Person;
which accepts all your examples.