ST 4U 283: DoesNotUnderstand Abuse
Today's Smalltalk 4 You looks at how it's easy to use - and abuse - #doesNotUnderstand: in Smalltalk. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:
If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.
You can also watch it on YouTube:
Today we'll look at #doesNotUnderstand: - and how you:
- Can override it to change the way an object behaves
- Should never do this lightly - it can create situations where your application fails in very hard to understand ways
First, we'll load the SimpleCounter application we used as an example for WebServices, and add this method:
doesNotUnderstand: aMessage | arg dict | dict := Dictionary new. dict at: #one put: 1. dict at: #two put: 2. dict at: #three put: 3. arg := dict at: aMessage selector ifAbsent: [nil]. arg := arg isNil ifTrue: [0] ifFalse: [arg]. self perform: #addValue: with: arg
Notice what this does - it treats a few strings as numeric arguments, and then converts anything it doesn't understand into a send of #addValue: with an argument of zero. That seems great - no more MessageNotUnderstood exceptions here. However, consider a more interesting object doing something like this, and passing values down the chain (maybe to a database, eventually). If you're lucky, you only get bad data. If you're unlucky, you get bad data and very, very odd application behavior.
Note the following workspace code:
counter := Counter new. counter one. counter two. counter three. counter thousand. counter goAway
All of that now "works" - or at least, none of those message sends break immediately. However, a follow on developer who sees the sending of #goAway, and looks for an implementor will find 26 nothing. That's the danger here. The code is now much more difficult to understand.
Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.
Technorati Tags: smalltalk, va smalltalk, mnu
Enclosures:
[st4u283-iPhone.m4v ( Size: 4741560 )]