Thursday, May 30, 2013

JS hashmap as interface tree for inherited hierarchies

If you ever need this, last night made converter from JSON to class inheritance hierarchy
{Exception:{IOException:{StreamException:{OpenStremException:function(){} }}}} - for Exceptions hierarchy

{Marker :{Relative:{prev:function(n){this.index=n;},prev1:0,prev2,... }
,Absolute:{abs:function(n){},abs1:0,abs2:0,... }}}  - for Parameters reference

You could find that useful for marking of input field types in form generator.

There are few JS patterns where pure class inheritance have much sense. Exceptions are among them.
OOP defines the pure interface as a class with methods or members declarations but without their implementation. Even if method/member will be defined by JS implementation there is no need for declaration in interface class itself. For example in given hierarchy

  • Exception - IOException - StreamException - StreamOpenException

only final (StreamOpenException) could hold some data like URI or redefined toString() method. On exception handling code only the hierarchy could be used. Data like URI  could be utilized mostly for non-functional (logging) code. If there is a rare need to (re)define implementation members, the function in hashmap serves as constructor. I.e. will be valid to say new exceptions.StreamOpenException(myURL). Methods could be defined within constructor via assignment. I.e.
StreamOpenException: function(URL){this.toString=function(){return this.URL;}}
will override parent string conversion inside of StreamOpenException constructor.

Another application for pure hierarchy definition would be parameters markers:
  • $w().xhr(...)..title().innerHTML( $w.prev, $.prev2 )
where $w.prev and $w.prev2 are instances of Marker(above) hierarchy. For convenience $w.prev, $w.prev1,$w.prev(1) referencing same entity, which is result of previous operation on chain. In sample above it is title attribute.

Happy coding!