views:

103

answers:

2

Hey,

I'm implementing a few things in Ruby and I was wondering how much error checking is appropriate (or, more precisely, how much error checking should be done by convention)?

For example, I'm implementing a method which swaps two elements in an array. The method is very simple:

def swap(a,b)
  @array[a], @array[b] = @array[b], @array[a]
end

It's really simple, but is it ruby-ish to check whether the given indexes are valid, or is that an unnecessary overhead (bearing in mind I do not intend for the method to work with wrap-around values like -1)?

A: 

It depends on the behavior that you're looking for. The Array#[] method that you're calling will do that check for you and return nil if you're using a nonexistent index, so I don't see a need to duplicate the error checking if you want that standard behavior. If you want something else, you'll need to implement the behavior you want.

However, this method will work with an index of -1, so if you want to disallow that, you will need to put a check for that.

Basically, I think a good rule is: Check for conditions in which your method will behave incorrectly, and implement the behavior you want. The out-of-bounds index condition will be caught by the array and handled a certain way -- if that handling is correct, you don't need to do anything. An index that does not match some custom expectation of the method will not be caught at all, so you definitely need to check for it.

Chuck
+3  A: 

I can't help you with negative indexes, but you can use

@array.fetch(a)

to raise an exception if a is an invalid index.

I ought to use fetch when I regard an invalid index as a "Can't happen" case, but sometimes I think only about the "happy path" scenario.

Andrew Grimm