Wednesday 23 December 2015

Structural Typing and Dynamic Languages

The other day I read for the first time about Structural Typing. Nothing particularly revolutionary, but interesting anyway. It tends to be defined as a sort of Compile-time duck-typing for static languages. Scala seems to be the most "mainstream" language implementing this feature.

Duck typing is one of the basis of dynamic languages. You don't consider that an object is suitable for an action depending on a strict contract like its type, but in a much more relaxed "having whatever methods I need" kind of contract. Structural typing allows us to indicate those methods that we require that an object sports. The advantage of this over directly grouping those methods in an interface is that as we are not forcing classes to implement an interface we can apply it to existing classes without modification, the compiler we'll provide the safety by checking that the class really has those methods.

I think being able to define a set of methods that an object needs to have could be a useful addtion to duck typing in dynamic languages. Let me explain:


function doSomething(ob1){
ob1.method1();
//do something more
ob1.method2();
}

In the above case, we could receive an object that has method1, but not method2 (it's a "partial duck" not a "full duck"), so our doSomething function would not fail until it calls to method2. Depending on what this code really does, running it only partially would be useless or even dangerous (so that we could need some sort of rollback)

So it could be interesting to have something like this:


function hasMethods(ob1, methodNames){
//returns boolean
}

function doSomething(ob1){
if (hasMethods(ob1, ["method1", "method2"])){
ob1.method1();
//do something more
ob1.method2();
}
}

No comments:

Post a Comment