«

»

Aug 26

Why my code is broken….. (break my code redux)

Yesterday, I posted an article entitled Break my code, please, wherein I posted a very fragile piece of code, with the challenge to find ways in which to break it.

What follows is a discussion of the code and why it is bad/fragile/easily broken…..

In the first place, methods like tr! and slice! behave differently than their non-bang’d relatives, tr and slice.  In general, methods which end in ‘!’ act upon the object, potentially changing it.  Also, by convention, if the method does not change the object, then nil is returned.  In the code there are many cases where it is possible for values to be passed in which do not affect the object, thus returning nil.  Because the methods are executed in order, with the result of the first being used as the object on which the next is performed, often methods can be invoked on nil (which doesn’t work very well).  Also, beyond code which is brittle and prone to failure, there is also code which can potentially cause confusion.

I’m attaching a commented version, which contains rspec tests; I’ll also include it here.

In conclusion, I’d like to highlight the following:

  • Differences between methods ending in ‘!’ and their non-adorned cousins
  • method_missing and it’s super
  • Not all types/objects respond to the same message — it’s a good idea to innoculate yourself.
  • Sometimes, behaviour is non-intuitive, so testing for boundary cases is a good idea.

I’d love to see other examples of “fragile” code, if anyone cares to share.

Leave a Reply

%d bloggers like this: