Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Reflection and Metaclasses

doesNotUnderstand: and Proxies

Learn how Smalltalk handles unknown messages with doesNotUnderstand:, and use it to build proxies, loggers and null objects. Real code is read-only; JavaScript Proxy stand-ins run here.

When you send a message and no class in the lookup chain defines it, Smalltalk does not give up. It packages the message into a Message object and sends doesNotUnderstand: to the receiver. The default implementation opens the debugger with the familiar "MessageNotUnderstood" error. But the method is an ordinary one, so you can override it, and that turns an error hook into one of the most flexible tools in the language.

In this lesson you will see what the Message object holds, how to override doesNotUnderstand: to build a logging proxy and a null object, and what to watch out for. The Smalltalk code is read-only here; the JavaScript Proxy examples are runnable stand-ins that behave much like these patterns.

What the failed lookup produces

SMALLTALK
3 fly.
"MessageNotUnderstood: SmallInteger>>fly"

Behind the scenes the virtual machine creates a Message with the selector #fly and an empty argument array, then sends 3 doesNotUnderstand: thatMessage. A message has two useful parts (read-only):

SMALLTALK
Object subclass: #Spy
    instanceVariableNames: 'log'
    package: 'Demo'.

Spy >> doesNotUnderstand: aMessage
    log ifNil: [ log := OrderedCollection new ].
    log add: aMessage selector -> aMessage arguments.
    ^ nil

aMessage selector is the symbol and aMessage arguments is an array of the arguments. Now Spy new foo: 1 bar: 2 is recorded instead of failing.

Pattern 1: the logging proxy

A proxy stands in for another object and forwards every message to it. Because doesNotUnderstand: catches whatever the proxy does not define, one method covers any interface (read-only):

SMALLTALK
ProtoObject subclass: #LoggingProxy
    instanceVariableNames: 'target'
    package: 'Demo'.

LoggingProxy >> doesNotUnderstand: aMessage
    Transcript show: 'sending ', aMessage selector; cr.
    ^ aMessage sendTo: target

Inheriting from ProtoObject instead of Object matters: Object already defines printString, =, class and dozens of other messages, so a proxy built on it would answer them itself instead of forwarding. ProtoObject is nearly empty, which makes it the right root for forwarding objects.

JavaScript has a built-in feature of this kind. A Proxy with a get trap sees every property access, so it can log and forward just like doesNotUnderstand:.

JS Stand-in: a logging proxy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The target never learns it was observed, and the calling code is unchanged. That is the same promise a Smalltalk proxy makes.

Pattern 2: the null object

A null object answers every message with itself (or a harmless value) so callers can skip ifNil: checks. It is easy to write with doesNotUnderstand: (read-only):

SMALLTALK
Object subclass: #NullLogger package: 'Demo'.

NullLogger >> doesNotUnderstand: aMessage
    ^ self

Now logger info: 'x' and logger error: 'y' do nothing, and logger info: 'a'; error: 'b' still chains. Real code often prefers explicit methods because they show up in the browser, but a null object built this way works for any interface.

JS Stand-in: a null object that swallows messages

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pitfalls

  • Hidden typos. A catch-all swallows acount deposit: 5 without warning. Forward only the selectors you expect, and call super doesNotUnderstand: for the rest so the debugger still opens.
  • Debugging confusion. A proxy that forwards printString or class hides what it really is. Decide which messages the proxy answers itself.
  • Speed. Failed lookup is slower than a normal send. Cache hot selectors by compiling real methods once you see the pattern repeat.

A safe version in Smalltalk (read-only):

SMALLTALK
Spy >> doesNotUnderstand: aMessage
    (target respondsTo: aMessage selector)
        ifTrue: [ ^ aMessage sendTo: target ]
        ifFalse: [ ^ super doesNotUnderstand: aMessage ]

This idea connects directly to reflection, because respondsTo: and perform: are what a forwarding proxy relies on. Next you will look at the call stack that every such message creates in thisContext and the Execution Stack.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when no class in the chain defines a selector?

    The VM builds a Message and sends doesNotUnderstand: to the receiver, which by default opens the debugger.
  2. 2. Why should a forwarding proxy inherit from ProtoObject?

    Messages the proxy inherits are answered locally instead of reaching doesNotUnderstand:.
  3. 3. What does a null object typically return from doesNotUnderstand:?

    Returning self lets cascaded and chained sends keep working without checks.
  4. 4. What is the safest way to catch only some selectors?

    Calling super keeps typos visible by opening the debugger as usual.

Summary

  • An unknown message becomes a Message sent via doesNotUnderstand:.
  • Override it to build proxies, loggers and null objects that work with any interface.
  • Root forwarding objects at ProtoObject so nothing is answered locally by accident.
  • Always let unknown selectors fall through to super unless a catch-all is the point.
  • The JavaScript Proxy examples are stand-ins; the Smalltalk code is read-only.

Next: thisContext and the Execution Stack