|
An interesting read, though perhaps it would have benefitted from going the route that made things click. After all, each of the features can be independently achieved, so why not show that _before_ winding around to the "whole bag" of OOP? (1) encapsulation, realized in Ada by private types. Package Geometry is
Type Point is private;
Function Create( X, Y : Integer ) return Point;
Function X( Object : Point ) return Integer;
Function Y( Object : Point ) return Integer;
Procedure X( Object : in out Point; Value : Integer );
Procedure X( Object : in out Point; Value : Integer );
Private
Type Point is record
Data_X, Data_Y : Real:= 0.0;
end record;
Function X ( Object : Point ) return Integer is (Object.Data_X);
Function Y ( Object : Point ) return Integer is (Object.Data_X);
Function Create( X, Y : Integer ) return Point is
( Data_X => X, Data_Y => Y);
End Geometry;
(2) reuse, realized in Ada via generics. Generic
Type Item is private;
One : Item;
with "*"(Left, Right : Item) return Item is <>;
Function Generic_Exponent( Base : Item; Exponent : Natural ) return Item;
-- ...implementation
Function Generic_Exponent( Base : Item; Exponent : Natural ) return Item is
(case Exponent is
when 0 => One,
when 1 => Base,
when 2 => Base*Base,
when others =>
-- Rule: X**2k = (X**k)**2; X**2k+1 = (X**k)**2 * X.
(Generic_Exponent(Base, Generic_Exponent(Base, Exponent/2), 2)
* (if Exponent mod 2 = 1 then Base else One);
);
(3) inheritance, realized with type-cloning. Type Temperature is range -40..2_000;
Type Probe_Range is new Temperature range -20..200;
(4) abstract interfaces, without touching OOP, arguably generics. (See above; note how we're depending on the type, a "one value", and a "multiply" operation.)
(5) type extension, for extending types you finally have to buy into OOP. Type Base is null record;
Function Text(Object : Base) return String is ("[]");
Type Color is ( Red, Green, Blue, Black, White );
Type Colored_Thing is new Base with record
Color_Data : Color := Red;
end record;
Function Text(Object : Colored_Thing) return String is
('[' & Color'Image(Object.Color_Data) & " ]");
(6) dynamic dispatch. -- Gets text from user.
Function Prompt return String; -- def elsewhere.
-- Gets a previously saved object.
Function Get( Name : String ) return Base'Class; -- def elsewhere.
Unknown_From_User : Base'Class renames Get( Prompt );
--...
-- The following will print "[]" if it is BASE, and
-- "[ COLOR ]" when COLORED_THING, replacing 'COLOR' with
-- the textual representation/literal for the value.
Ada.Text_IO.Put_Line( Unknown_From_User.Text );
|