Why I stopped inheriting from ruby’s core Array class and why you shouldn’t inherit from ruby’s core classes too

An article, posted almost 3 years ago filed in workbook, gem, rubygems, ruby, inheritance & performance.

Inheritance is considered bad practice for quite some time now (Gamma, Helm, Johnson & Vlissides, 1994). Little did I know when I started the ‘workbook’-project in 2012 (note that I don’t have a computer science background).

Why I stopped inheriting from ruby’s core Array class

The main reason I wrote this workbook-gem was that I wanted the most predictable API for working with spreadsheet data (acting as arrays of arrays), not having to use a different API when reading XLSX or CSV files, nor when writing it.

After learning that inheritance is not always a good thing, I still often thought of a workbook as an array of arrays and hence an exception to the rule. But then I came accross a helpful post by Avdi Grimm: Why you shouldn’t inherit from Ruby’s core classes (and what to do instead). Of course, a lot of what I wanted from the ruby core Array-class could also be offered by including Enumerable.

Performance improvement?

So while still thinking of a workbook as a 4-dimensional array, I put up the challange just for the sake of improving my ruby skills. It took a few days to make all tess pass again. And while I don’t think the code cleaned up by a lot, which was something I had hoped for, I was most surprised to see that my tests ran ~25% faster. First the tests ran in about ~9,8s, now they finished in ~7,3s (even with some additional assertions). This might be a huge advantage for reading and writing larger workbooks.

It is now obvious to me why. I had been reimplementing a lot of fast, C-compiled code, in ruby. This not only ran slow because of ruby, but also because I created alternative ways of accessing data within the array structure (e.g. not only finding a value in a cell by an index, but also the header column name, or finding a cell from a table using the typical spreadsheet reference, e.g. “A2”).

Keep challenging what you think you know

Today I’ve also closed an almost 6 year old self requested feature that asked for inheriting from ruby core classes for the cell values.

While this story might be quite specific to a little project I am maintaining, it is especially important to challenge your ideas about how things should work when you’re maintaining something mostly on your own.

Photo by Ylanite Koppens from Pexels

Op de hoogte blijven?

Maandelijks maak ik een selectie artikelen en zorg ik voor wat extra context bij de meer technische stukken. Schrijf je hieronder in:

Mailfrequentie = 1x per maand. Je privacy wordt serieus genomen: de mailinglijst bestaat alleen op onze servers.