Object-oriented design in Fortran

The last seven lessons built the machinery of object-oriented Fortran one feature at a time. This lesson puts it together and asks the design question instead: when does a type belong in a hierarchy, and when is the right answer a type that simply holds another one? The example is a report that has a formatter, not a report that is one, and the formatter is swapped while the program runs.

What the language gives

Four things, and they are enough for most library design. A derived type groups components; a type-bound procedure keeps an operation with its data; an abstract type with deferred bindings is an interface; and a class() variable or dummy is the polymorphic slot where any implementation goes. Extension adds a child, overriding changes a binding, and select type recovers the concrete type when a procedure needs it.

What the language does not give is the other half of the list: no constructors in the C++ sense, no destructors except a finaliser with the two gaps of the previous lesson, no multiple inheritance, no interfaces separate from types, no generics over types (a parameterised type is the closest thing), and no garbage collector. A design that needs those is a design that will fight the language.

An abstract formatter

The interface is a type with two deferred bindings, a header and a row, each declared by an abstract interface with import. Two children implement them: a CSV formatter, which prints a comma-separated header and rows, and a plain formatter, which prints a title with an underline.

The file oop.f90:

module reporting implicit none private public :: formatter, csv_formatter, plain_formatter, report type, abstract :: formatter contains procedure(header_iface), deferred :: header procedure(row_iface), deferred :: row end type formatter abstract interface subroutine header_iface(self, title) import :: formatter class(formatter), intent(in) :: self character(len=*), intent(in) :: title end subroutine header_iface subroutine row_iface(self, name, value) import :: formatter class(formatter), intent(in) :: self character(len=*), intent(in) :: name real, intent(in) :: value end subroutine row_iface end interface type, extends(formatter) :: csv_formatter contains procedure :: header => csv_header procedure :: row => csv_row end type csv_formatter type, extends(formatter) :: plain_formatter contains procedure :: header => plain_header procedure :: row => plain_row end type plain_formatter type :: report class(formatter), allocatable :: fmt character(len=8) :: title = 'report' contains procedure :: render => report_render end type report contains subroutine csv_header(self, title) class(csv_formatter), intent(in) :: self character(len=*), intent(in) :: title write (*, '(a,a)') trim(title), ': name,value' end subroutine csv_header subroutine csv_row(self, name, value) class(csv_formatter), intent(in) :: self character(len=*), intent(in) :: name real, intent(in) :: value write (*, '(a,a,f8.2)') trim(name) // ',', '', value end subroutine csv_row subroutine plain_header(self, title) class(plain_formatter), intent(in) :: self character(len=*), intent(in) :: title write (*, '(a)') trim(title) write (*, '(a)') '----------' end subroutine plain_header subroutine plain_row(self, name, value) class(plain_formatter), intent(in) :: self character(len=*), intent(in) :: name real, intent(in) :: value write (*, '(a,f8.2)') trim(name) // ' = ', value end subroutine plain_row subroutine report_render(self, n) class(report), intent(in) :: self integer, intent(in) :: n integer :: i character(len=8) :: name call self%fmt%header(self%title) do i = 1, n write (name, '(a,i0)') 'item', i call self%fmt%row(name, real(i) ** 2) end do end subroutine report_render end module reporting program oopdemo use reporting implicit none type(report) :: r r%title = 'squares' allocate(csv_formatter :: r%fmt) call r%render(3) deallocate(r%fmt) allocate(plain_formatter :: r%fmt) call r%render(2) end program oopdemo

gfortran -Wall -Wextra -std=f2018 oop.f90 -o oop
./oop

squares: name,value
item1, 1.00
item2, 4.00
item3, 9.00
squares
----------
item1 = 1.00
item2 = 4.00

Composition: a report HAS a formatter

The report type does not extend formatter; it holds one in a component declared class(formatter), allocatable. That is the difference between is-a and has-a, and it pays three times in this example. A report can change its formatter without being a different type. A formatter can be used by anything else, since it knows nothing about reports. And a report type can later gain a second collaborator, a data source or a filter, without a parent type to extend.

Inheritance would have been the wrong tool here: a CSV report is not a kind of formatter, and a formatter that contained a report would be a cycle. The hierarchy exists once, for the interchangeable part, and the object that uses it is a plain type with one polymorphic component.

Swapping at run time

The last five lines of the output come from the same report with another formatter. The deallocate and the second allocate change the dynamic type of the component, and render was compiled once. A program that reads a format name from its command line is five lines away from this: select case on the name, one allocate per branch.

The same statement could have been an assignment, r%fmt = plain_formatter(), which reallocates the component to the new type and copies the (empty) value. Both routes need the component to be allocatable, and neither needs the report to know which formatter it holds.

What the language does not give

No constructor means a type that must be valid from the first line needs a module function that returns it, which is the pattern of section 072. No destructor in the C++ sense means a resource released in a finaliser may not be released for an array element or for a main-program variable in this build, which section 081 showed. No interfaces separate from types means every interface costs a type declaration and an abstract interface.

The missing piece that hurts most in a large program is generics over types: a container of points and a container of matrices are two types, and the language has no way to write one container for both. The workarounds are a container of class(base) with a common abstract base, which forces every element into the hierarchy, or a preprocessor, which the language does not have either. For a numerical library this is usually fine, because the elements are numbers; for a container library it is the reason most Fortran containers are written twice.

A child that is not complete

A concrete child must implement every deferred binding. Leave one out and the compiler tells you which one, at the declaration of the child:

module reporting_bad implicit none type, abstract :: formatter contains procedure(header_iface), deferred :: header procedure(row_iface), deferred :: row end type formatter abstract interface subroutine header_iface(self, title) import :: formatter class(formatter), intent(in) :: self character(len=*), intent(in) :: title end subroutine header_iface subroutine row_iface(self, name, value) import :: formatter class(formatter), intent(in) :: self character(len=*), intent(in) :: name real, intent(in) :: value end subroutine row_iface end interface type, extends(formatter) :: csv_formatter contains procedure :: header => csv_header end type csv_formatter contains subroutine csv_header(self, title) class(csv_formatter), intent(in) :: self character(len=*), intent(in) :: title write (*, '(a)') trim(title) end subroutine csv_header end module reporting_bad

gfortran -Wall -Wextra -std=f2018 -c badchild.f90

badchild.f90:23:43:

23 | type, extends(formatter) :: csv_formatter
| 1
Error: Derived-type 'csv_formatter' declared at (1) must be ABSTRACT because 'row' is DEFERRED and not overridden
badchild.f90:23:43:

23 | type, extends(formatter) :: csv_formatter
| 1
Error: Derived-type 'csv_formatter' declared at (1) must be ABSTRACT because 'row' is DEFERRED and not overridden

The message names the missing binding, and the same text appears twice in this build, once for each pass the compiler makes over the type. The two ways out are both legitimate: implement row, or declare the child abstract when it is a partial implementation meant to be extended again.

A guide for a small hierarchy

Four rules cover most Fortran designs. Put the interchangeable behaviour in an abstract type with deferred bindings and give it the smallest interface that the users need. Hold it in a component of the type that uses it, so that the user is not in the hierarchy. Keep the number of levels at two, because a third level costs a select type branch everywhere and buys nothing a second component cannot. And write the factory as a module function that returns class(base), allocatable, so that no caller names a concrete type.

Everything else is the same judgement as in any language: a hierarchy is for values that a caller should be able to replace, not for code sharing. In Fortran the code that is shared is usually a module procedure that takes the abstract type, which is a plain subroutine and easier to read than a method.

Exercises

  1. Add a third formatter that prints the rows as a markdown table. How many lines does it take, and which lines of report change?
  2. Replace the two allocate statements with assignments r%fmt = csv_formatter() and r%fmt = plain_formatter(). Does the program still compile and run?
  3. Give report a second component, integer :: width = 8, and pass it to the header binding. Which interface changes?
  4. Write a function make_formatter(name) result(f) that returns class(formatter), allocatable chosen by select case. What does it return for an unknown name?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why does the report hold a formatter instead of extending it?

    Answer

    A report is not a formatter; composition keeps the two interchangeable and separate

    HAS-A, not IS-A.

  2. What does class(formatter), allocatable :: fmt allow?

    Answer

    Any concrete formatter to be put in the component at run time

    The polymorphic allocatable component carries the dynamic type.

  3. What does this program print? module m implicit none type, abstract :: fmt contains procedure(iface), deferred :: tag end type fmt abstract interface function iface(self) result(s) import :: fmt class(fmt), intent(in) :: self character(len=8) :: s end function iface end interface type, extends(fmt) :: t1 contains procedure :: tag => t1_tag end type t1 contains function t1_tag(self) result(s) class(t1), intent(in) :: self character(len=8) :: s s = "ONE" end function t1_tag end module m program p use m implicit none class(fmt), allocatable :: f allocate(t1 :: f) print *, f%tag() end program p

    Answer

    ONE

    The one child implements the deferred binding.

  4. What is missing in Fortran compared with C++ for generic containers?

    Answer

    Generics over types, so a container is written once for all element types

    A container of class(base) or two containers are the workarounds.

  5. How is a type made valid from its first line without a constructor?

    Answer

    A module function returns the constructed value

    The function is the public name of the construction.

  6. What does gfortran say when a concrete child leaves a deferred binding out?

    Answer

    The type must be ABSTRACT because the binding is DEFERRED and not overridden

    The message names the binding that is missing.

  7. How many levels of extension does the lesson recommend?

    Answer

    Two: the abstract base and its concrete children

    More levels cost select type branches without a gain.

  8. What should a factory return so that no caller names a concrete type?

    Answer

    class(base), allocatable

    The dynamic type stays inside the factory.

  9. Which of these does Fortran NOT provide?

    Answer

    Multiple inheritance

    A type extends one parent only.

  10. What does swapping the formatter of a report at run time cost?

    Answer

    A deallocation and an allocation; render was compiled once

    The component changes its dynamic type; the code does not change.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image