When I came to ruby I knew that in Ruby Everything Is An Object, but until I started writing “real” code, I didn’t realize that the Ruby world works that much better if your code is object oriented as well.
Case in point my simple Twitter to HTML program. When I first wrote it, it was pretty much written from the point of view of where I was at, a old and functional programming Perl coder.
So what is the difference between the styles of functional programming and object oriented programming? For me, this meant that I was basically writing a program with no classes defined with a top to bottom program flow. There was a “main()” (if you are familiar with C programming) which basically ran a set of functions and then ended.
Ruby itself discourages you from doing this. There isn’t (as far as I can tell) the concept of pre-defining functions, so you have to write functions that you use before you use them. So if you have a line that calls “foo(x,y)” you have to make sure that you have foo() defined above that in the program. and if foo() calls bar() then bar has to be defined above foo(), and so on. Not fun if you want to make your source code readable and nicely laid out.
Once I let Ruby’s object oriented nature take over a bit though, and defined the functionality in a class, and then just created an instance of the class to do foo() and bar() operations, it didn’t matter in what order code was assigned in the file, because the entire class is parsed by the interpreter before anything is done to it*.
* I’m sure this isn’t 100% true from a compiler / systems design point of view, but for the end user that’s basically what it looks like.
So what else does this give you, or more specifically, force you to do? Well, lots or Rubyist type things. This encourages you to…
- create your programs in terms of data types (“this is a thing”)
- group functionality together (“this thing does these operations”)
- create objects that function together or off of each other (“this thing is a sub or superset of this other thing”)
- ensure your methods play nicely (ie: method chaining)
As many have said before, you can write bad C code in any language, but I had to come to the realization that just because I was writing in Ruby didn’t mean that I didn’t have to change how I was programming to take the most advantage of it.
Not that every program needs to be “objectified”, that 10 liner to parse out some some text and insert it into a database probably doesn’t need to be split into 2 modules and get 100% code coverage, but then again, maybe you’ll re-use it again next week, or maybe it’ll turn into the central convert-everything utility program for your job, and if so, wouldn’t it be nice if it was OO and tested from the start, instead of having those “extra” bits of safety tacked on after it becomes apparent that it’s more than just a quick and dirty little hack? (For me it’s happened way too often that I don’t realize this until way too late….)