My struggle for professionalism

set of conclusions about software development

ORM (NHibernate, EntityFramework) Linq ToList() and all you can do wrong.

Hello,
I have really little time lately and lot of thoughts to write a post. Let's persist one of them before it will disappear for next 6 months (to next project with unefficient SQL access layer).
What I'm about to write is true for any ORM since ORM is no more that mapper from SQL to some object notation. I will focus on .NET Linq /NHibernate examples since this is my current area of work.

I'm seeing it over and over again.

session.Query<Users>().Select(x =>new MyDTO{
Name = x.Name,
SecondName = x.SecondName,
BirthDateString = x.BirthDate.ToString("dd/MM/yyyy")
}).ToList();

And the code breaks with "Specified method is not supported" so programmer puts .ToList() before .Select( and everything works like a charm from now on! Does it?

Well if there is no other columns and we are not about to filter this data it is acceptable. But usually it is not a case. Usually table contains lot of columns we do not need. Like 10 times more data that we actually want to fetch.  

Writing

session.Query<Users>().ToList()

causes full Users table to be fetched from SQL server to web server (with all not used columns like description, photo, etc....) which usually means that we get throught network (that is thougth the slowest hardware component in most of the cases) far more data that we need.

What is the source of the problem here? Well in general it is mixing data layer, business layer and presentation logic all together in one place, more specific it is because NHibernate (or EntityFramework - doesn't really matter) do not know how to translate .ToString("dd/MM/yyyy")to SQL query and therefore it throws exception. What we shoud do to fix it? Separate data retrieval from formatting !! Even by a single line:

Code like that will do the trick (which doesn't mean it is how it should look like in well-crafted code !).

session.Query<Users>().Select(x =>new {
Name = x.Name,
SecondName = x.SecondName,
BirthDateString = x.BirthDate
}
).ToList().Select(x =>
new MyDTO{
Name = x.Name,
SecondName = x.SecondName,
BirthDateString = x.BirthDate.ToString("dd/MM/yyyy")
}).ToList()

We define anonymous object referencing Name, SecondName, BirthDate and by that we signalize to ORM that this are only columns from "Users" we care about (so ORM is not about to download any other from SQL Servier).

then first ToList materialize that query. then second Select do the formating (this should be other class or method at least in clean code) second ToList() transform collection back to desired type.

I Hope this will help some beginning programmers not to create messy (and slow!) code any more.


Happy coding!



 

Jasmine.js part1

In several previous posts (1,2) I've been writting what should be done to make code testable.
But when you have testable code, How to actually test it?

Well this is where Jasmine.js comes in.

It has quite staight-forward documentation so I will not elaborate too much about it.
Instead of that, let's look at TODO application.
I've added several files to this project:

todo/tests/businessLogicSpec.js

todo/tests/uiModuleSpec.js

This are tests definitions for BusinessLogic and uiModule accordingly.
How to see results of that tests. Well simplest way is to add specrunner.html file (included in jasmine package),
replace invalid paths to js files with valid one and run all.
There are three group of files we nid to include.
Jasmin libraries:
  <script src="jasmine.js"></script>
  <script src="jasmine-html.js"></script>
  <script src="boot.js"></script>
Tested Module File:
<script src="../Scripts/App.js"></script>
Specifications:
  <script src="../tests/businessLogicSpec.js"></script>
  <script src="../tests/uiModuleSpec.js"></script>
and the and result should be similar to:
SpecRunner

Now when we know how to setup environment let's go to writing tests.

Jasmine is BDD testing framework therefore it puts importance on readable descriptions.

let's look at some example:

describe('businessLogic',function(){

    var bl = undefined;
    beforeEach(function() {
        var app = APP;
        bl = app.businessLogicModule();
    });
..................

it('should have 1 elements after add and sort',function(){
//initialization
 var elemCount = -1;
var elemVal = undefined;
//filling with data
  bl.insertElement("aaaa");
//setting up reciver that will watch data (part of public BL interface)
 bl.UpdateListCallback(function(data){ elemCount = data.length; elemVal = data[0].Value; });
//sorting collection
  bl.sort();
//asserting test conditions
 expect(elemCount).toBe(1); });
..............
});//end of describe


in orange we can see couple of jasmine functions:

  • describe

container describing a module or other logical part of application, describe can be nesteed in other describe (which states for structure of modules and submodules)

describe('Main module',function(){
describe('Sub Module',function(){

});
describe('Other sub Module',function(){

});
});
  • beforeEach/afterEach

should be one per describe. For every testcase ('it' call) beforeEach is being called before testcase and afterEach is called after testcase execution

  • it

testcase. Take as first parameter description of itself and as second callback that should contain expect expression to evaluate result of a testcase.


So, in forEach we setup bi object that is BussinessLayer module.

Then in it mwthod we can see several typical steps:

  • initialization
  • filling with data
  • setting up necesary callbacks
  • doint tested thing
  • asserting test condition


That is basic usage of Jasmine framework. In later parts I will describe it more specifically.



Happy coding!


_.js (Underscore.js)

Underscore is simple but very powerfull library.

Following the description from authors page:

      It’s the answer to the question: “If I sit down in front of a
      blank HTML page, and want to start being productive immediately, what do I need?”

It is set of helpers methods for manipulation of:

  • Arrays
  • Objects
  • Functions

I will describe couple most commonly used - for full reference see library page.

How many times you write:

for(index = 0;index<mydata.length;index++){
 //some code using mydata[index] and index
}

well there is another way without explicit declaration of index

_.each(mydata,function(element,index,myDataReference){
 //some code using element (mydata[index])  index or array itself
});

how about filtering?

Assume we have array of objects:

var myData = [{name:'Adam',age:31},{name:'Kate',age:29},{name:John, age:44}]
and we want to filter records with age < 40

var peopleUnder40 = _.filter(myData,function(x){ return x.age<40});
we have also :
  • sortBy
  • groupBy
  • every
  • some


It is not that rare that by calling some api we get array of objects that contains some useless data among data we actually queried for. Here is where map comes in.

var newData = _.map(myData, function (x){ return { Caption : x.name, ageInDays : x.age*365 } });


Another set of usefull utility functions are :

  • bind (bind context to function)

If You remember my post about closure here and here You remember a case of current loop index value encapsulation.This is what bind is for. If You have function like this:

function printInfoOfCurrentItem()
{

      console.log("Id :"+this.Id);

      console.log("Name :"+this.Name);

      console.log("SecondName :"+this.SecondName);

}

You will notice that there is "this" keyword in use.

by calling

var bindedHandler = _.bind(printInfoOfCurrentItem,{Id:1,Name:'John',SecondName:'Galt'}) ;

from now on call of bindedHandler

will call it as this was set on passed object.

  • partial (preset values of some function parameters)

Sometimes in certain part of application we call a function with part of parameters set always to the same value.

This is where partial comes in.

Let's say we have method that wraps ajax call

function call (baseUrl,queryString,method,callback){
......
}

and we call it like below:

call("http://mydataserver.com","listName=People&id=7","GET",doStuffWithUser);
and since we are always calling http://mydataserver.com and we are reading data so we are using get method we might find an alias usefull
var getData = _.partial(call,"http://mydataserver.com",_,"GET",_);
from now on calling

getData("listName=People&id=7",doStuffWithUser);
will be exact equivalent of
call("http://mydataserver.com","listName=People&id=7","GET",doStuffWithUser);
  • memoize (caching)


  • once (only first call)

  • after (for synchronisation - run once after bunch of async req)

  • throttle (for ignoring user maniacally clicking refreash)

Bridge pattern

Hello again,

Some time ago, I've promised to describe bridge pattern.
FIrst it is good idea to explain what a bridge pattern is all about.

Simplest explanation is:
Bridge is two way Adapter ;).

Well good example of bridge pattern is in fact this one:
Two way Adapter

You may have hdmi reciver (like monitor) and DVI signal source, or the another way around. Both will work.
Because of that producents of Computer Monitors do not need to bother about what will be the interface of signal source as long as there exists adapters (usually 100 times less complex that communicating devices).

OK, lets skip this abstract example and consider some more programming-related example.

Lets imagine todo list:
  • Textbox to enter a value 
  • Button to submit textBox value
  • Header row to sort listed values
  • removal of a row performed by clicking on it

what kind of functionality should UI of that application provide?

  • Well it should be able to consume some array of data and display it the way it like.
  • It should as well notify that button were click.
  • It should also notify that row where click (and which row)
  • It should allow to read current value of textbox on request

Let sum briefly what is not UI responsibility:

  • UI should not make decisions what action is performed on row click
  • UI should not decide what to do while header is clicked

working application can be found here


so UI_MODULE would looks like follows:

UI_MODULE=function(){
//IMPLEMENTATION (...)
function consumeDataF(someArray){
init();
  for(i=0;i<someArray.length;i++){ var row = addRow(data[i]);
bindRowClickCallBack(row);
  } }
function buttonClickCallBackSetter(callback){
//implementation (...)
}
     return {             consumeData:consumeDataF,             registerButtonClickCallBack:buttonClickCallBackSetter,             registerHeaderClickCallBack:headerClickCallBackSetter,             registerRowClickCallBack:rowClickCallBackSetter     
}
}

What kind of functionality on the other hand should BusinessLogic provide?

  • should store list
  • should sort list
  • should add item to the list
  • should remove selected item from a list
  • should decide when list need update

What kind of things it should not think about :

  • how list is represented
  • what launches sort event
  • what launches delete row event

According to that requirements BUSINESS LOGIC should look like follows:

BL_MODULE=function(){
//implementation (...)
var refreshUI = function()
{
if(dataConsumerCallBack){
dataConsumerCallBack(elements);
}
};

//delete example
var deleteF = function (value){
elements = elements.filter(function (el, idx, array) {
return el !== value; // for objects it means equality of reference
});
refreshUI();
}

return {
sort: sortF,
deleteItem:deleteF,
insertElement:insertF,
UpdateListCallback: registerCallback
}
};


Well, now we have two modules with totally distinct interfaces. How to bind it to actually working application ?

Well this is where Bridge comes in.

We want to have a code like that:

 var bridge = app.bridgeModule(uiModuleInstance,businessLogicInstance);
 bridge.wireUpAndRun();

That will link all parts of application and run it.

How does it look like? Not that compex:

blModule.UpdateListCallback(uiModule.consumeData);
uiModule.registerButtonClickCallBack(blModule.insertElement);
uiModule.registerHeaderClickCallBack(blModule.sort);
uiModule.registerRowClickCallBack(blModule.deleteItem);

And that makes all of the application to work.

sometimes providing requirements of an interface by services of another interface is not that simple. In case of that code of a bridge become complex. The real aim is not to have simple bridge, but to ensure that if one of the modules change drammatically all others are untached. Only bridges can change and even that happends only if changes of module includes redefinition of its interface.  As in real life Island are usually 100 times larger and more complex than bridges that connects them as well in programming usually bridge is far simplier than module and provides perfect separation.


Bridge pattern strongly supports Open-Closed  principle which states for O in S.O.L.I.D. .  It highly uplifts flexibility of a software. It also enforce D (dependency inversion) from mentioned acronym and supports I (interface separation) and S(single resposibility). I've found this pattern extremly usefull in programming clean, easy to modify applications.


Happy coding

Require.js

This post will be the first about external libraries that makes javascript developer life easier. No it will not be about jQuery. There is tons of stuff in the internet about it and I really do not see reason to add some new.

Managing dependencies in javascript is quite annoying thing.
Every time we add new js file we need to add <script tag> to all html files that uses it. What is more, we must keep in mind that scripts are loaded in order they are occuring on the page and code should handle that. 

Let consider simple example, typical hello world application.
Code for it is available here:
Greet Me

This application (which, by the way, is not a state of the art design) contains 3 files:

ui.js   - containing all operations on ui
businessLogic.js  - contains logic what to do when click event occurs
app.js  - module that wires up previous two together.
 
Lets have a look on ui.js

(function(){
    document.APP = document.APP || {};
    document.APP.UI=function(){

        var bl;  //BusinessLogic object
        var clickHandler = function(){
            bl.reactOnClick();  //handling click event by Business logic
        };

        var setTextF = function(x){
            var elem = document.getElementById("Label");
            elem.innerHTML=x;
        };

        var provideInputTextF = function(){
            var elem = document.getElementById("textBox");
            var val = elem.value;
            return val;
        };

        var setHandlers = function(){
            var control = document.getElementById("button");
            control.onclick=clickHandler;
        };

        var setBL = function(b){  //creepy setter setting dependency to business Layer
            bl = b;
        };

        setHandlers();   //Setting event handler for a button during module instantiation

        return{  //return of public interface of a module
            setBusinessLogicProvider:setBL,
            setTextOnLabel:setTextF,
            provideInputText:provideInputTextF
        }
    }
})();

This UI depends on Business logic (by function setBL) and Business logic depends on UI. Of course this is a bad design and it could be eliminated by applying Bridge Pattern (I promise to describe it in future posts), but applying pattern like that to such a simple application is clearly an overdesign. 

it is important to notice that APP.UI function is not executed in that file. It is also important to notice that by having more than one file we couldn't avoid creation of global variable APP. It is not a disaster as long as we have only one, but couldn't we do better?

Before answering that question lets look on businessLogic.js file:

(function(){
    document.APP = document.APP || {};
    document.APP.BusinessLogic=function(ui){
        var reactOnClickF = function(){
            var txt = ui.provideInputText();
            txt = "Hello, "+txt;
            ui.setTextOnLabel(txt);
        };
        return{
            reactOnClick:reactOnClickF
        }
    };
})();


it defines single public method which decides what to do on click event. It reads text box, prefix text with "Hello, " and outputs modified text back to the UI. As it is operating on UI it has dependency on it. In conjunctions with UI dependency on BusinessLogic (described earlier) it leads to circular dependency(which is clearly bad design, but not that rare anyway).

This circular dependency is solved by setBusinessLogicProvider (mapped to private setBL) method in UI public interface.

Lets look on third file to see how it is wired up together.

window.onload=function(){
    (function(){
        var ui = document.APP.UI();
        var bi = document.APP.BusinessLogic(ui);
        ui.setBusinessLogicProvider(bi);

    })();
};

 First, windows.onload need to be used to ensure that all methods will be xecuted when page is ready.
After that we insantiate UI then BusinessLogic and then we pass reference of business logic to the UI that works only because click event is delayed until user actually presses the button. This third file (in conjunction with setBL method) should be somehow avoided.

Let's look at second version of an application that uses require.js :

Greet Me better

If you take a look on html file, you will se that there is only one script reference

  <script data-main="app/ui.js" src="lib/require.js"  type="application/javascript"></script>

this script tag contains not standard attribute 'data-main' that is set to the path of main solution file of an application. Why it is not app js? Because app js will no longer be needed, what will be shown later. In new application version

Lets look on begining of ui.js file:

require.config({
    baseUrl: "/requireTests2/app",
    paths: {
        "txt": "../res"
    },
    waitSeconds: 15
});

what you can see here is require.js basic configuration.

baseUrl defines site-relative path to js file. for example if we define later on reference as 'BusinessLogic' it will be resolved as

/requireTest2/app/BusinessLogic.js

that is baseUrl+passedName+'.js'

paths: contain list of aliases of paths related to the base path

for example 'txt/resource' will be resolved as 'requireTest2/app/../res/resource.js' that is 'requireTest2/res/resource.js'

wait second is timeout of js scripd loading. Default is 7 seconds.


Lets have a look at clickHandler in UI.js:

        var clickHandler = function(){
            require(['BusinessLogic'],function(bl){
                bl.reactOnClick();
            });
        };

it call require global function with list of dependencies as first parameter and a callback with one argument for each dependency called asynchronously when all dependencies are loaded.

to see that mechanism better lets have a look on on BusinessLogic.js

define(['ui','txt/resource'],function(ui,res){
        var reactOnClickF = function(){
            var txt = ui.provideInputText();
            txt = res.greetPrefix+txt;
            ui.setTextOnLabel(txt);
        };
        return{
            reactOnClick:reactOnClickF
        }
    }

in here main function has two dependencies :

  • ui
  • res

therefore array has two arguments as well as callback.

So calling in clickHandler that depends on BusinessLogic calls back dependency on UI (which is already loaded since onClick event is user triggered and asynchronous) and on resource.js (throught txt alias) which provides current prefix for message.

So, what we have achieved, is set of dynamically injected modules. Word 'dynamically' contains one other nice feature. That is asynchronous script load which helps to decrease page load time. If you look at 

Greet Me better

requests you will see that BusinessLogic.js and resource.js is not loaded at the begining with load of a page but after button click.

If your code is well design and loosely coupled you will be able to split page load into several independent stages.

Closure

I've written about closure a little in post about ajax calls. If you want to read about closure look here:

W3schools, and more complete (and complicated) jibbering
or to the code - single line of code might mean more than a thousand words ;).

(function(){
var bar=null;
var fux=null;
(function(){
var i=0;
var foo = function()
{
return function(){
i++;
return i;
}
}
var baz = function(){
return function(){
i++;
return i;
}
}
fux = baz();
bar = foo();
})();

(function(){
alert(bar()); //bar
alert(fux()); //fux
alert(bar()); //bar
alert(fux()); //fux
alert(bar()); //bar
alert(fux()); //fux

alert(bar()); //bar
alert(fux()); //fux
})();
})();


if you run this code you will notice 8 alerts with incrementing value from 1 to 8. What is interesting about bar and fux function is that they both have access to local variable 'i' which exists for them even if it cames from self invoking function that do not exist anymore. So the fact that first self-invoking function left two references (bar and fux) to their own private functions (foo and baz) cause persistance of 'i'. It can be seen during execution of second self-invoking function (series of alerts) which scope is distinct from the first one. What is more, both private functions foo and baz uses same local variable 'i' and shares single instance of it.

Let's look on some other example

(function(){
var executor =
function(){
var i=0;
var foo = function(){
i++;
return i;
};

var baz = function(){
i++;
return i;
};
return {
fooExec:foo,
barExec:baz
}
};
var exe1 = executor();
var exe2 = executor();
alert(exe1.fooExec());
alert(exe1.barExec());
alert(exe2.fooExec());
alert(exe2.barExec());

})();

Here I define executor method which returns references to foo and baz functions. What differs this example from the previous one is fact that exe1 object executions do not affect in any way exe2 object.


Closure can provide an context for method invocation(they become statefull) as well as data encapsulation (privat variables).

It also can be used to pass to the callback variables that are not supported by API (see ajax example)

It is one of the most powerfull features of javaScript, providing to programmer great expressiveness of a language.


happy coding!

Javascript - counterintuitive stuff part 2

Today I will talk about two things - Parenthesis and references.

In most of the language it is not important for code execution what and how many whitespaces you put in it.

well for javaScript that is false.

Let's consider the code:


function Test(){
return
{
id:42
}
};
function Test2(){
return{
id:42
}
}
console.log(Test());
console.log(Test2())l

Are both invocations about to return same value?

well, no. Test() will return 'undefined'. Why? Because javaScript compiler transforms Test() to following code:
function Test(){
return; // here is automatically inserted semicolon
{
id:42
}
};
It is called 'Automatic semicolon insertion'
therefore it is always good to place opening bracket at the end of the line, like:

if(.....){


}

 Ok,
second strange javaScript feature is references.
If i show You the code:

someObject ={value:1};

function someObjectOperation(){
return this.value;
}

someObject.bar = someObjectOperation ;
var alias =
someObject.bar;



function referenceCaller(ref){
ref();
};

alert(
someObject.bar()); //ok
alert(
referenceCaller(obj.bar)); //undefined
alert(alias()); //undefined

Would you expect that all three alerts return same value? Well i did. I expected that passing function as parameter do not change behaviour of that function, as well as aliasing it. But I was wrong.

while first invocation returns someObject.value following returns undefined ;).

So if you are about to use this in functions assigned to objects never use aliases of them ;). It is because parent object is detached from function when you pass that function as reference. Oh, and just by the way if you do that mistake with a function that assigns values to this instead of reading them you are about to pollute global scope.

happy coding.

Javascript - counterintuitive stuff part 1

Most of programing languages has some things you would not expect from them. I believe JavaScript has an extraordinary portion of those.

Let's go throught some of them.

We can declare functions in two ways:

var foo = function(){

}

function bar(){

}
Are both of the ways equal and is it just matter of preference which one to use or not exacly?
Lets consider the code:

   if(bar!==undefined){
bar();
}
function bar(){
console.log('bar');
}
if(foo!==undefined){
foo();
}
var foo=function(){
console.log('fooo');
}
test it

What we see as output is:

bar 1
bar 2
foo 2

That means that foo was undefined at the moment of first invocation. While bar was available in full scope.
So the difference is that declaration with use of var limits scope to invocation after declaration
when declaration with use of "function name(" syntax extends scope to full parent function body.

Speaking about variable declaration scope:

people programming in C++, C# used to thing that scope of variable visibility is limited by block boundries {}. Unfortunatelly it is not fully true for JavaScript

Lets consider the code:

    var condition = true;
if(condition){
var i=1;
}

console.log(i);
It might suprise You but it is about to work. It will output 1 to the console.
What might be even more suprising, this code is also about to work
    var condition = true;
var condition2 = true;
if(condition){
var i=1;
}

if(condition2){
var i=2;
var i=3;
console.log(i);
}
There is no such thing as variables naming conflicts in javascript. this code outputs 3 to the console.
Because of that it is very good practice to declare all your variables at the begining of the function, like that:

   var condition = true;
var condition2 = true;
var i=1;
if(condition){
i=1;
}

if(condition2){
i=2;
i=3;
console.log(i);
}
It clearly shows what is going on.

Of course concept of variables scope is implemented in JavaScript, but on the function level:

   var i=0;
function foo(){
var i=1;
console.log(i);
};
foo();
console.log(i);
the output of this function is:
1  (from foo invocation)
0  (from global invocation)
So the global value of i exists independly from the local value of i.

There is more tricky thing about variables declaration called 'implied global'.

(function(){
    var i=0;
    function foo(){
        i=1;  
        j=2;
        console.log(i);
    };
    foo();
    console.log(i);
    console.log(window.i);//undefined
    console.log(window.j);
})();

in here I forgot to add var keyword in foo i and j declarations. It results in two things:
  •  foo overrides value 0 of i variable setting it to 1 (which is reasonable )
  • foo declares global variable j (which is crazy)

To avoid stuff like that start your every script with:

"use strinct";

line, that will tell the browser to interpret script differently. Any use of variable without declaration will cause an error.


happy coding!

Ajax callbacks and additional data

JavaScript supports asynchronous requests. It is both: source of enormous power of javascript and potential source of bugs in hard to maintain cluttered code. To exemplify the problem in clear way I will use jQuery.ajax method and jsFiddle /echo/json service

Lets assume we want to do 10 asynchronous calls to some external service. In callBack we want to be aware which iteration number it is:
incorrect code example

var i=0;
for(i=0;i<10;i++){
    $.ajax({
        url:'/echo/json/',
        dataType:'json',
        type:'POST',
        data: {
            json:JSON.stringify({a:1,b:2}),
            delay:3
        },
        success: function(data){
          console.log('Iteration '+i+' '+JSON.stringify(data)+' returned')
        },
        fail:function(data){alert('Fail');}
    });
}

example above perform 10 requests and 3 seconds after request returns with response object {a:1,b:2} - this object would be normally fetched from external source so we cannot put there anything. What need to be done is  passing 'i' variable value in the moment of ajax call and somehow persisting it untill success function is invoked.

Code above works incorrectly because at the moment of success method invocation (3 sec after request) all iterations of loop are being completed and value of i is set to 10.

Main source of a problem is that all success functions shares the same i variable. Solution of this problem is to use feature of javaScript called closure

correct code example

this code example differs from the previous one in that as a success handler it assiggn result of invocation :

generateBindedSuccessHandler(i)
let's look at generateBindedSuccessHandler code:

generateBindedSuccessHandler = function(index){
var successHandler = function(data){
console.log('Iteration '+index+' '+JSON.stringify(data)+' returned')
};
return successHandler;
}
so function define a variable successHandler (which is also a function) and returns it. Since successHandler runs in scope of generateBindedSuccessHandler body and uses index variable. Index value will be remembered until any reference to successHandler exists. It is important to understand that every invocation of generateBindedSuccessHandler produces different instance of successHandler therefore different copies of index will be stored for each reference. This feature called 'closure' is one of strangests (and most powerfull) features of javaScript. Understanding it is crucial for efficent javaScript development.


Happy coding!

Encapsulation and code structure in javascript - part 2

Three days ago I've started to describe encapsulation in javaScript.

Any nontrivial project contains more than one file. If it comes to javascript, linking files together is not trivial task. The only way to link several files is by use of global namespace (global variables). At the same moment we shoud limit usage of global variables to the minimum. We should also ensure that our code is modular to achieve testability.  There are great tools (like requirejs) that helps us achieve that. For now, in order to better understand how libraries like that works, we are not about to use them.

Let assume our application has 3 modules:

  • UI
  • BusinessLogic
  • DataAccess
 and linking module called App. Application externally depends on jQuery.

Dependency tree Looks like following:
  • App
    • BusinessLogic
      • UI
        • jQuery
      • DataAccess
        • jQuery
As there are 4 modules there are also 4 files.


//UI.js
var ASKR_EXMPL_APP = ASKR_EXMPL_APP||{};
(function()
{
var app = ASKR_EXMPL_APP;
app.UI = uiModule;
function uiModule(jQ){
return({/*Public interface of module*/});
}
})();


in first line we conditionally defines single global variable (ASKR_EXMPL_APP)

Syntax : ASKR_EXMPL_APP || {};

means that if first operand is falsy (in this case undefined or null) second operand is being assigned, otherwise self assignment is performed (so nothing change)

that means that we will end up with exacly same global object structure no matter in what order scripts are loaded. (the only assumption is that linking module is loaded at the end - we could bypass this as well by attaching App.js function to DOM ready event but for simplicity of a code this is skipped).

Another important observation is that uiModule function requires additional parameter (jQ) which means that external dependency on jQuery is not direct but indirect throught module instantiation code. This is very important from testing perspective because it allows us to replace jQuery with a mock if necessary (for example to be notified about jquery invocations in code).


//DataAccess.js
var ASKR_EXMPL_APP = ASKR_EXMPL_APP||{};
(function()
{;
var app = ASKR_EXMPL_APP;
app.DATA_ACCESS = dataAccessModule;
function dataAccessModule(jQ){
return({/*Public interface of module*/});
}
})();

DataAccess.js doesn't really differs from  uiModule so it do not need any additional comment.

//BusinessLogic.js     
var ASKR_EXMPL_APP = ASKR_EXMPL_APP||{};
(function()
{
var app = ASKR_EXMPL_APP;
app.BUSINESS_LOGIC = businessLogicModule;
function businessLogicModule(uiModule,dataAccessModule,jQ){
return({/*Public interface of module
exposing .runApp() function*/

runApp:function(){}});

}
})();

Well BusinessLogic is third module wiring both previous together. As You can see it takes three parameters: uiModule, dataAccessModule, jQ. This approach allow to replace whatever necessary to test solution efficiently. 

Last file is App.js .This anonymous function plays role of primitive factory wiring modules together. As we can see it's only place where for example jQuery ($) is used explicitly (as well as global references to different modules).

//App.js
(function()
{
var app = ASKR_EXMPL_APP;
var instance = app.BUSINESS_LOGIC(
app.UI($),
app.DATA_ACCESS($),
$
);
console.log(ASKR_EXMPL_APP);
instance.runApp();
})();

Building application this way isolates modules from each other encouraging good loosely coupled design.

Happy coding!