HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

OOP Dependency Inversion Principle

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
inversionprincipledependencyoop

Problem

I made an example for learning Dependency inversion principle in JavaScript OOP programming .

String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function textHandler(){

    this.printRedbox = function( ){
        return ' Red Box text ';
    }

    this.printBluebox = function( ){
        return ' Blue Box text ';
    }
};

function htmlHandler( handler ){

    var block = [],
        box  = document.getElementById('container');

    this.boxContentHandler =  handler ;

    this.setType = function( handler ){
        this.boxContentHandler = handler
    };

    this.appendBlock = function( html ){

        block.push( html );
        box.innerHTML = block.join('');
    };

    this.printBox = function ( action ){

        var title = this.printTitle() ,
            text  = this.boxContentHandler[ 'print'+ action.ucfirst() ](),
            html  = ''
                        +   title + text
                    +'' ;

        this.appendBlock( html );
    };

    this.printTitle = function( ) {
            return 'Title ' + block.length + ' ';
    };
};


Here I am doing the action handling part

var htmlHandle = new htmlHandler(  new textHandler()  );

document.getElementById('bluebox').addEventListener( 'click', function(){
    htmlHandle.printBox(  this.id );
},false );            

document.getElementById('redbox').addEventListener( 'click', function(){
    htmlHandle.printBox(  this.id );
},false );


I would like to know, is there a way to make it better. Did I miss anything here ?

Solution

This is a decent way to implement Dependency Inversion, from the standpoint of your implementing classes. The only improvements I would recommend is to find a good class library that does the lookup of dependencies for you.

Really Inversion of Control/Dependency Inversion involves several parts:

  • Writing your classes so that they receive their dependencies via one of three methods:



  • Constructor injection (like you have) new Foo(x)



  • Property injection a.foo = b



  • Setter injection a.setFoo(b)



  • An object factory that can turn a class name in the form of a String into a new object



  • An dependency resolver that does the lookup of dependencies and injects them into a new object



  • A "container" object allowing you to configure your dependencies and wire your classes together



I've created Hypodermic for this purpose, though I think it should be refactored to separate the "container" from the "dependency resolver" functionality. I would be interested in finding out if there are other Dependency Injection libraries out there for JavaScript.

Context

StackExchange Code Review Q#28273, answer score: 5

Revisions (0)

No revisions yet.