Overridable Class Attributes in Ada 2012

One of the nicest features of the AdaCore website is the Ada Gem of the Week. Currently sitting at 117 gems, this place is a regular treasure-trove for Ada programming.

Today’s gem is written by Emmanuel Briot and it deals with some of the new Ada 2012 features, specifically in relation to object oriented Ada programming. it’s called Gem #117: Design Pattern: Overridable Class Attributes in Ada 2012.

Most object-oriented programming languages provide a facility for declaring variables that are shared by all objects of a given class. In C++, these are called “static members” (and use the “static” keyword), and similarly Python has the notion of “class attributes”.

Let’s consider an example where this is useful. For instance, let’s say we want to define the notion of a block of text that is generated by expanding a template (perhaps after we replace some parameters in that template, as can be done with AWS’s templates parser, for instance). Once we have computed those parameters, we might want to generate multiple outputs (for instance HTML and CSV). Only the template needs to change, not the computation of the parameters.

I can’t say I’m a huge expert on object oriented Ada programming, but this little snippet actually made me hungry for playing around with some of the new Ada 2012 features, such as expression functions, where you can do stuff like this:

pragma Ada_2012;
 
type Text_Block is tagged null record;
function Template (Self : Text_Block) return String
   is ("filename.txt");
function Render (Self : Text_Block) return String;

Instead of the old more clunky method:

type Text_Block is tagged null record;
function Template (Self : Text_Block) return String;
function Render (Self : Text_Block) return String;
 
function Template (Self : Text_Block) return String is
   pragma Unreferenced (Self);
begin
   return "file_name.txt";
end Template;

Very nice indeed! The new Ada 2012 syntax allows for a much more simple and readable setup of the Text_Block type. But don’t take my word for it, go read the Gem instead. It is definitely worth it.

One thought on “Overridable Class Attributes in Ada 2012”

Leave a Reply