Sunday, April 26, 2009

Forget Me Not! Object Oriented Design in Custom Exception

When designing custom exceptions, you may forget about old school OO fundamentals. As a reminder, lets take a look into the following custom exception classes.


StorySaveError
StoryDescopeNotAllowedError
StoryCompleteError
StoryNotFoundError
StoryDeleteError
StoryDeleteNotAllowedError

These exceptions are really useful in my application. But the bad thing is, they all derive from StandardError class, whereas there should be a base class, may be StoryError, which is more meaningful and useful. So, we can have the following-


class StoryError < StandardError
end
StorySaveError < StoryError
StoryDescopeNotAllowedError < StoryError
StoryCompleteError < StoryError
StoryNotFoundError < StoryError
StoryDeleteError < StoryError
StoryDeleteNotAllowedError < StoryError

With the addition of a base class for all Story related exceptions, I can write cleaner/better code.

  • When I am not interested about the specific error, I can just use rescue StoryError to catch 'em all
  • I can place a common error handling routine for all Story related exceptions
  • I can add new exception types without altering the codes where the specific type of StoryError is insignificant

From my experience, I found that most people are not cautious about OO when desiging custom exceptions. (because they are exceptions!). Nonetheless, if you follow the OO guides, it will pay off for sure.