Trait implementation check

13 views
Skip to first unread message

sheerun

unread,
Apr 17, 2011, 2:06:44 PM4/17/11
to traits.js
I don't see the way to check if given object implements specified
trait.

For example, when making an Tree, each node has to implement Node
trait (Tree trait operates on methods and proporties of Node trait, so
it should check in some way if function's attribute implements Node
trait).


Some pseudocode:

var Tree = Trait({
insert: function(node) {
if( ! node.implements(Node))
throw "Node has to implement Node trait";

// ...
}
});

How is it possible?

Tom Van Cutsem

unread,
Apr 18, 2011, 9:00:28 AM4/18/11
to trai...@googlegroups.com
Hi sheerun,

A pertinent question. Currently, traits.js does not provide any operator to test whether an object was instantiated from a particular trait. In principle, traits are not meant to be used as a type/classification mechanism. This is better left to a separate mechanism. Unfortunately, Javascript's only built-in mechanism for such type tests (the "instanceof" operator) relies on single-inheritance of prototypes, which is not directly compatible with trait-based inheritance.

I see two workarounds:

1) instead of performing a type test, test for the presence of particular properties that your code depends upon (this fits within the "duck typing" philosophy of dynamic languages such as Javascript <http://en.wikipedia.org/wiki/Duck_typing>)

2) if you really need to distinguish based on type rather than behavior (e.g. a Tree Node and a Tree Leaf presumably implement the same interface), the simplest workaround is to add a dedicated property to the trait to distinguish between these types, for instance, add an { isLeaf: <boolean> } property.

Hope this helps.

Kind regards,
Tom

2011/4/17 sheerun <sh3...@gmail.com>

sheerun

unread,
Apr 19, 2011, 4:07:22 PM4/19/11
to traits.js
Hello,

> 2) if you really need to distinguish based on type rather than behavior
> (e.g. a Tree Node and a Tree Leaf presumably implement the same interface),
> the simplest workaround is to add a dedicated property to the trait to
> distinguish between these types, for instance, add an { isLeaf: <boolean> }
> property.

Actually, in my case Tree Leaf would be Trait, so I would check
behavior rather than type. isLeaf seems a good solution, though.

In perfect case, Trait would check if used properties belong to
particular trait only when creating a real object (I mean Trait.create
method), and at run-time (when using crated objects), properties
existence would be presumed (because of performance). Although,
currently I do not see the way to do it.

If you'll have some other ideas, please share it. And thanks for
response!
Reply all
Reply to author
Forward
0 new messages