Main Content

Why you should use objects even for short data manipulation programs in Ruby

Archive - Originally posted on "The Horse's Mouth" - 2012-06-10 06:41:30 - Graham Ellis

It's so easy to take the "Bull at a gate" approach - to start writing code to do the job in hand without giving thought to code-reuse later on, or indeed to how the work can be used again later. And it's double easy to, for me to take the bull approach during a course, where I'm writing a short demonstration piece that won't be developed further, where the specification of the demo develops as we write it, and where I don't have the time, delegate patience, nor need to invest in adding a good, re-usable set of underlying classes for later use ... simply because (unusually) there is no "later"! Unfortunatley, this means that I can end up with a piece of code thatshows poor maintainabiity, and if there is a wish to re-use or develop it later, that becomes harder, and I may even need to refactor.

I'm describing here the conundrum of "do I use an OO approach, even if my little utility is so tiny that it doesn't naturally take to being object based?" If the initial language is an OO language such as Python or Ruby, then the answer is probably YES, I should always start with the OO paradigm. And indeed on our courses in these inherrently OO languages, we introduce classes and objects as early as is practical.

Enough theory - let's take a practical example from last week's course.

I have a data file containing passenger data from UK railway stations, including the number of passenger journeys made to or from each stations on an annual basis from 2004. (Data file is based on Office of Rail Regulation data which is publicly available - view [here] or download [here]). And I wanted, as a quick demonstration to come up with a list of the top ten stations, growthwise, over the period in question.

Initial answer - [here] - a short piece of code but (frankly) with some messy alorithm stuff in the main code, and not easily re-used.

Object based answer - and extended into a really useful application which allowed me to understand some of the information hidden in the data - [here].

The object based example illustrates:
• Static methods and variables in Ruby
• Defining your own comparator for sorting
• attr_reader - for direct but controlled access to an object variable
• Using a factory pattern
• to_s to make an object printable
• the % method on a string object for formatting data
• returning multiple results from a method call
• lazy operators such as and