Frage

I want to redefine smalltalk's nil to work like the one in objective-c. So when nil receives a message that it can't handle, it returns nil. Now I know that nil is just a shortcut for UndefinedObject but is there anything like method_missing in Ruby so I can redefine it in UndefinedObject to always return nil?

War es hilfreich?

Lösung

The method you are looking for is called doesNotUnderstand: in Smalltalk. You can indeed implement:

UndefinedObject>>doesNotUnderstand: aMessage
    ^ nil

However, keep in mind that this affects the complete system and might have subtle side effects or introduce bugs in other parts of the system.

Also note that UndefinedObject is not a primitive type, but a normal class inheriting from Object. Therefor nil already understands a large number of messages and might not behave as you would expect coming from Objective-C.

Andere Tipps

Consider creating your own Null singleton class that implements #doesNotUnderstand: so that you don't modify nil. Make the super class nil (like Object).

Answer something like '^Null instance' instead of '^nil' in cases where you want it.

Null instance badMethod  --> nil

If you're the only person who will ever work on this code, I say go for it.

On the other hand, if this is a product owned by some company which is not a synonym for "you", and someone else may at some time have to maintain this, I strongly recommend that you NOT do this. Modifying classes at the heart of Smalltalk is one of THE classic ways to blow your toes off. (I knew a guy once who did this. He was not happy...and always limped a bit after that. Funny old thing, life...).

Share and enjoy.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top