Posted by James Mead
Tue, 07 Aug 2007 17:05:00 GMT
Recently Luke and I spotted a subtle bug in our code where we were mistakenly assuming a method returned an Array when it actually returned a Fixnum. We were then calling the #size method on the result, but interestingly Fixnum#size returns the number of bytes in its machine representation.
Previously I had noticed that my colleague Paul Battley tended to use Array#length in preference to Array#size. Now I know why, or at least I know why I’m going to start using Array#length! If we’d used #length in this case we would have seen a NoMethodError instead of the spurious value, 4.
[5,6].size
1.size
[5,6].length
1.length
Update: Josh Susser has posted a useful related article about the use of…
Tags array, bug, length, machine, representation, ruby, size | 4 comments
Posted by James Mead
Thu, 15 Feb 2007 03:42:00 GMT
I just read Tim Ottinger’s post about Tuple Madness. Coincidentally yesterday afternoon I wondered out loud whether Ruby’s rich collection classes encouraged more than the usual amount of what I call inside-out code – where a client object queries another object for its internal data and manipulates that data into the required form.
This works well in the small, but can quickly lead to similar manipulations happening in multiple client classes. Also unless you’re careful, it can harm readability – e.g. where the meaning of a bit of data depends on its position within an array.
As time marches on, I feel more and more like a bear of very little brain who can keep less and less code in his head at any one time. As a defence against this I try to…
- write or extract small classes with clear and simple responsibilities
- limit low-level access to the internal data of the class
- write simple unit tests clearly expressing the intent of the code.
I hope these tactics don’t just help me, but help other developers who later need to understand and modify the code I’ve written.
Tim has a nice summary…
I don’t think that “magic tuples” are always evil, only that they’re no substitute for proper objects and meaningful data structures.
Tags array, collection, data, demeter, encapsulation, hash, ruby, set, tuple | no comments