I'm writing a library for sparse linear algebra computations as a backend for my thesis work and I've come to a bit of a crossroads. I'm using modern Fortran (don't groan, it's had inheritance and polymorphism and all that jazz for 10 years now).

From a software design standpoint, my main issue was making iterative solvers be able to use sparse matrices without knowing what storage format they're in. The only functionality that an iterative solver has to know about is how to multiply a matrix by a vector.

I did this by having an abstract class sparse_matrix with a virtual method matvec for matrix-vector multiplication; then there were several child classes, representing each storage format, which override the parent matvec with their own implementation. I believe this is called the "template" pattern yes?

I'm considering refactoring my code to use composition over inheritance. To that end, a sparse matrix consists of an underlying graph with some extra data -- sometimes it's an array of real or complex numbers, sometimes an array of dense matrices, etc. There are multiple different sparse matrix formats which use the same underlying graph storage scheme. Every sparse matrix has a graph object as an attribute, and has a collection of function pointers which change to use that graph in different ways. Before, I had to effectively redefine the same graph storage scheme for each sparse matrix format that used it.

The advantages I can discern are:

  1. fewer classes make it easier to hook my code up to C/C++/Python
  2. easy to choose different parallel implementations of the same algorithm; write every implementation and redirect function pointers at runtime. Before I had to use big conditional blocks.
  3. I think this design will be easier when the underlying graph is better thought of as a hyper-graph, and matrices as heterogeneous compositions of several matrices in possibly different formats. (This happens in some PDE applications.)

Can anyone think of a good reason why I should stick with the old inheritance-based design? If the new approach is more sensible, any advice beyond what's said in GoF would be appreciated.

  • Why not use MATLAB? It supports lots of linear algebra operations on sparse matrices.
    – Dima
    Commented Jul 29, 2013 at 22:35

1 Answer 1


My read is that the inheritance-based approach was correct.

What you fundamentally want is a matrix-vector product operation, that your solvers can call. The solvers don't care how the matrix OR the vector are stored in memory. All they care about is being able to multiply them and get back the result. That is just about the canonical use case for a polymorphic approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.