Interfaces in dynamic object-oriented languages (part 2)
In the first part I suggested to use messages like to_my_interface or asMyInterface to ensure interface-compliance. This method just returns whatever object seems to be suitable for the interface, but does no actual checks. IDE like Xcode or Eclipse can do a static check for implemented methods and issue warning/error at compile time. Today I will show how to build the same feature in the dynamic system (and make it more useful).
First, two important points from the first part:
One object (sender) send a message to another (receiver) with an argument which should implement String interface (receiver will call asString method on its argument).
1. The sender does not need to perform any “casting” before sending an interface-compliant object. If appendString(obj) wants a string and you know that your object can (or should) behave like a string, you just pass it in without any conversion. Only low-level method which relies on actual string methods like substring should send asString to obtain the String interface.
2. The receiver should not perform any checks like respondsToSelector or isKindOfClass. It should only tell the argument to return something with an interface it needs.
If both sender and receiver do not check actual interface compliance, where should it happen? Obviously, inside the asString method:
# this method does not check the interface
def asString
self
end
# this method checks the interface
def asString
String.check(self)
end
How’s that different from just testing application as before? First of all, check is performed before any protocol message is send to the subject. So it is more like a “compile-time” check: some message could not be sent in runtime, but the error could be thrown before.
In addition to basic checks like missing methods String.check can also perform some unit tests (and be smart enough to test each particular class (hidden class) only once).
Needless to say that interface checks could be omitted in production mode to increase performance.
