Should a matrix software library have a root class (e.g., MatrixBase
) from which more specialized (or more constrained) matrix classes (e.g., SparseMatrix
, UpperTriangluarMatrix
, etc.) derive? If so, should the derived classes be derived publicly/protectively/privately? If not, should they be composed with a implementation class encapsulating common functionality and be otherwise unrelated? Something else?
I was having a conversation about this with a software developer colleague (I am not per se) who mentioned that it is a common programming design mistake to derive a more restricted class from a more general one (e.g., he used the example of how it was not a good idea to derive a Circle
class from an Ellipse
class as similar to the matrix design issue) even when it is true that a SparseMatrix
"IS A" MatrixBase
. The interface presented by both the base and derived classes should be the same for basic operations; for specialized operations, a derived class would have additional functionality that might not be possible to implement for an arbitrary MatrixBase
object. For example, we can compute the cholesky decomposition only for a PositiveDefiniteMatrix
class object; however, multiplication by a scalar should work the same way for both the base and derived classes. Also, even if the underlying data storage implementation differs the operator()(int,int)
should work as expected for any type of matrix class.
I have started looking at a few open-source matrix libraries and it appears like this is kind of a mixed bag (or maybe I'm looking at a mixed bag of libraries). I am planning on helping out with a refactoring of a math library where this has been a point of contention and I'd like to have opinions (that is unless there really is an objective right answer to this question) as to what design philosophy would be best and what are the pros and cons to any reasonable approach.