One change made in both: maintainability in Haskell and C++

Maintainability is not a property of a language, it is a property of a change. The same codebase is easy to maintain in one direction and awkward in the other, and the pair of changes below is the standard way to see which way a language leans: add an operation to a type that already has several cases, then add a case to the type.

The program is the shape example of the first page: a circle and a rectangle, with an area. The change is a perimeter. Both compilers have something to say about it, and the two answers are the best short summary of the difference between a closed sum type and an open class hierarchy.

One change, two programs

In C++ the operation belongs to the type, so it is a new pure virtual function in the base class and an override in every subclass that exists. In Haskell the operation is a function over the type, so it is a new function with a case and no change to the type at all. The two edits are different sizes, and the compilers check different things about the result.

A new operation in C++

The base class gains perimeter as a pure virtual, which is the declaration that says every shape must answer it. Circle is updated; Rect is the subclass somebody forgot, which is what a real change looks like in a codebase with more than one author:

#include <cstdio> #include <memory> #include <string> #include <vector> class Shape { public: virtual ~Shape() = default; virtual std::string name() const = 0; virtual double area() const = 0; virtual double perimeter() const = 0; }; class Circle : public Shape { public: explicit Circle(double radius) : radius_(radius) {} std::string name() const override { return "circle"; } double area() const override { return 3.141592653589793 * radius_ * radius_; } double perimeter() const override { return 2 * 3.141592653589793 * radius_; } private: double radius_; }; class Rect : public Shape { public: Rect(double width, double height) : width_(width), height_(height) {} std::string name() const override { return "rect"; } double area() const override { return width_ * height_; } private: double width_; double height_; }; int main() { std::vector<std::unique_ptr<Shape>> shapes; shapes.push_back(std::make_unique<Circle>(1.0)); shapes.push_back(std::make_unique<Rect>(2.0, 3.0)); for (const auto& shape : shapes) { std::printf("%s %.2f %.2f\n", shape->name().c_str(), shape->area(), shape->perimeter()); } }

g++ -std=c++23 -Wall -Wextra -O2 broken.cpp -o broken; echo "status $?"

In file included from /usr/include/c++/15.2.0/memory:80,
                 from broken.cpp:2:
/usr/include/c++/15.2.0/bits/unique_ptr.h: In instantiation of 'constexpr std::__detail::__unique_ptr_t<_Tp> std::make_unique(_Args&& ...) [with _Tp = Rect; _Args = {double, double}; __detail::__unique_ptr_t<_Tp> = __detail::__unique_ptr_t<Rect>]':
broken.cpp:39:44:   required from here
   39 |     shapes.push_back(std::make_unique<Rect>(2.0, 3.0));
      |                      ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~
/usr/include/c++/15.2.0/bits/unique_ptr.h:1085:30: error: invalid new-expression of abstract class type 'Rect'
 1085 |     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
broken.cpp:25:7: note:   because the following virtual functions are pure within 'Rect':
   25 | class Rect : public Shape {
      |       ^~~~
broken.cpp:11:20: note:     'virtual double Shape::perimeter() const'
   11 |     virtual double perimeter() const = 0;
      |                    ^~~~~~~~~
status 1

The compile fails, and the reason is in the middle of the block: an invalid new-expression of abstract class type 'Rect', because Rect does not implement a pure virtual of its base. The first six lines are the template instantiation that led there, and the note: lines name the function that is missing. The build stops, so the change cannot be shipped half done.

The same operation in Haskell

In Haskell the edit is one function, and the type does not change. The function below handles a circle and forgets the rectangle, which is the same half-finished change:

module Main (main) where import Text.Printf (printf) data Shape = Circle Double | Rect Double Double area :: Shape -> Double area shape = case shape of Circle radius -> pi * radius * radius Rect width height -> width * height perimeter :: Shape -> Double perimeter shape = case shape of Circle radius -> 2 * pi * radius main :: IO () main = do let shapes = [Circle 1.0, Circle 2.0] mapM_ (\shape -> printf "%.2f %.2f\n" (area shape) (perimeter shape)) shapes

ghc -Wall -O1 -o perimeter-hs Perimeter.hs
./perimeter-hs; echo "status $?"

[1 of 2] Compiling Main             ( Perimeter.hs, Perimeter.o )
Perimeter.hs:17:5: warning: [GHC-62161] [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In a case alternative:
        Patterns of type ‘Shape’ not matched: Rect _ _
   |
17 |     case shape of
   |     ^^^^^^^^^^^^^...

[2 of 2] Linking perimeter-hs
3.14 6.28
12.57 12.57
status 0

The program builds and runs, and the compiler says one thing: GHC-62161, the match does not cover Rect. A warning is not a failure, so the change can be shipped half done, and a program that passes a rectangle to perimeter dies at run time instead of failing to compile. The project that wants the C++ behaviour adds -Werror, and the course lesson on warnings and errors shows it.

That is the honest trade of the two checks. C++ refuses to build a program whose subclass is incomplete, and it does that per class. Haskell builds it and tells you which case is missing, and the choice between a warning and an error is a flag rather than a language rule. The Haskell warning also covers the case C++ has no equivalent for: a function that handles three of four shapes.

A new case in C++

The change in the other direction is a triangle. In C++ it is one new class that implements the two functions, and nothing else in the program changes: the loop over the vector already calls through the base class, so it picks the new shape up without an edit.

#include <cstdio> #include <memory> #include <string> #include <vector> class Shape { public: virtual ~Shape() = default; virtual std::string name() const = 0; virtual double area() const = 0; virtual double perimeter() const = 0; }; class Circle : public Shape { public: explicit Circle(double radius) : radius_(radius) {} std::string name() const override { return "circle"; } double area() const override { return 3.141592653589793 * radius_ * radius_; } double perimeter() const override { return 2 * 3.141592653589793 * radius_; } private: double radius_; }; class Rect : public Shape { public: Rect(double width, double height) : width_(width), height_(height) {} std::string name() const override { return "rect"; } double area() const override { return width_ * height_; } double perimeter() const override { return 2 * (width_ + height_); } private: double width_; double height_; }; class Triangle : public Shape { public: Triangle(double side) : side_(side) {} std::string name() const override { return "triangle"; } double area() const override { return 0.4330127018922193 * side_ * side_; } double perimeter() const override { return 3 * side_; } private: double side_; }; int main() { std::vector<std::unique_ptr<Shape>> shapes; shapes.push_back(std::make_unique<Circle>(1.0)); shapes.push_back(std::make_unique<Rect>(2.0, 3.0)); shapes.push_back(std::make_unique<Triangle>(2.0)); for (const auto& shape : shapes) { std::printf("%-8s %6.2f %6.2f\n", shape->name().c_str(), shape->area(), shape->perimeter()); } }

g++ -std=c++23 -Wall -Wextra -O2 open.cpp -o open
./open; echo "status $?"

circle     3.14   6.28
rect       6.00  10.00
triangle   1.73   6.00
status 0

Three shapes and no change outside the new class. The same change in Haskell is one constructor in the type and a warning in every function that matches on it, which the first page shows with both warnings. Neither answer is free: C++ pays when the operation is added and Haskell pays when the case is added.

What each compiler enforces

Change Haskell C++ When the error arrives
a new operation one function, no edit to the type a new pure virtual, an override in every subclass Haskell: warning per missed case. C++: build error per incomplete subclass
a new case a constructor, a warning in every match one new class, no other edit Haskell: warning per match. C++: nothing
a changed field a record update in every place that builds it a constructor call, a compiler error per wrong call both refuse a call with the wrong arguments

The reason to care is the shape of the codebase, not taste. A program whose set of types is stable and whose set of operations grows, which is most business software, is the case Haskell makes cheap, and the visitor pattern exists to give C++ the same cheapness at the price of two dispatches and a class per operation. A program whose set of types grows and whose operations are stable, which is most plugin systems and most user interface toolkits, is the case C++ makes cheap.

The second thing a compiler enforces is how big a change has to be. The C++ perimeter touched the base class, so every file that includes the header is rebuilt and every subclass anywhere, including one in a library, is affected; the Haskell function touched one module and nothing else. Where a program is compiled as a whole that difference is minutes, and where it is split into packages with a published interface it is a version bump.

The Haskell lesson for the closed side is sum types and exhaustive matching, and the next page in this set is What a reader of each language needs first.

The C++ programs were built with g++ 15.2.0 (Alpine 15.2.0) using -std=c++23 -Wall -Wextra -O2 and the Haskell program with GHC 9.10.3 using -Wall -O1, all run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image