Thursday, January 29, 2015

Exceptions are a primitive type

I hold that Exception is a primitive type, and so using one directly in your code is a common example of Primitive Obsession.

The antidote is to wrap the primitive in a Whole Value. It's a pretty straightforward transformation when your code looks like this:

- Make a new exception class, typically nested at the current scope.
- Name it based on the message text.
- Parameters to the message become parameters to the constructor and properties on the new class.
- Override the "Message" property to hold the string.Format() call.

Like this:
Like all good design moves, this helps testing.

Note that in the 2nd example, I'm separating "I expect this exception with these properties" from "the exception should be able to format itself like this". There's a nice separation of concerns.

1 comment:

Brian Geihsler said...

Haven't thought about Exceptions in this way. I like this idea, thanks for sharing.