Friday, September 19, 2014

Instance Pattern

Question: "How do I protect or hide functions or variables in JavaScript? "
                  "Can I use separate JS files or the Module pattern?"

Answer: Use the Instance pattern.

There are only 2 ways to get JavaScript into HTML:

 1. Inline - <script> some JavaScript </script>
 2. Link - <script src='main.js'></script>

I know this is obvious but we need that common ground for what comes next. ;)

JavaScript does not have the ability to "import" other JavaScript files into it's self.  All the "importing" is done in the HTML.  You can do this several ways:

 - Link each one individually into the HMTL
 - Dynamically link them in through some JavaScript
var script = document.createElement("script");
script.src = "all.js";
 - Library like RequireJS. RequireJS uses the Asynchronous Module Definition (AMD) API.  It is the JavaScript mechanism for defining modules such that the module and its dependencies can be asynchronously loaded.

It is import to consider reasons for separating JavaScript into separate files.

 - Maintainability - it becomes easier to work on one piece at a time
 - Readability - if everything is in one big file it is very hard to see what is what
 - Division of Labor - it is easier to have multiple developers working on multiple files instead of one big one
 - Reuse - all your functions can be broken up into highly cohesive modules

Separate JavaScript files DO NOT make things Private, Closures make things Private.

Now, consider at the end of the day when everything is ready for production the best thing you could do is Optimize your JavaScript by combining it all into one file so that the user only has one file to download.

When dealing with Private variables in JavaScript, you will at some point want to access them.

 - Public function - can be altered.
 - Privileged function - a Public function that can access the Private variable.
 - However if the function is in an Instance then it can only be altered in each Object.

Let me illustrate with some code.

var MODULE = (function () {
    //Private variables
    var privateParent,

    privateParent = 'parentPrivate';

    return app = {
        //Privileged method
        getPrivateParent: function() {
            return privateParent;

MODULE.sub = (function (parentApp) {
    //Private variables
    var childMessage,

    childMessage = ' - trying to access parent private field: ' + parentApp.getPrivateParent();  //prints parentPrivate

    Constr = function () {
        this.childF = this.childFunction();

    Constr.prototype = {
        constructor: MODULE.sub,
        version: "1.0",
        childFunction: function () {
            $("#testing-div").append(childMessage + "");
    return Constr;


//We could just as easily print to the console, but the 'append' allows us to display the results on the page.

$("#testing-div").append("This first part shows what does not work; everything is 'undefined'. " + "");
$("#testing-div").append("You are unable to access the var or func directly. " + "");
$("#testing-div").append("MODULE.privateParent = " + MODULE.privateParent + "");
$("#testing-div").append(" = " + + "");
$("#testing-div").append("MODULE.sub.childMessage = " + MODULE.sub.childMessage + "");
$("#testing-div").append("MODULE.sub.Constr = " + MODULE.sub.Constr + "");
$("#testing-div").append("MODULE.sub.childFunction = " + MODULE.sub.childFunction + "");
$("#testing-div").append("END lesson. You must access childFunction() through the new operator." + "");
$("#testing-div").append("----------------------------------------------------" + "");

$("#testing-div").append("Let's see if making an instance of the Object works" + "");
var test = new MODULE.sub();
test.childFunction(); //run the method
$("#testing-div").append("Looks like it did!!!!" + "");
$("#testing-div").append("----------------------------------------------------" + "");

$("#testing-div").append("Now let's try to change the childFunction() ?" + "");
test.childFunction = function() {$("#testing-div").append(" - This is a new function." + "");}
test.childFunction(); // altered version
$("#testing-div").append("Looks like it was changed. :(" + "");
$("#testing-div").append("----------------------------------------------------" + "");
$("#testing-div").append("Does it stay changed?" + "");
var test2 = new MODULE.sub();
test2.childFunction(); // doesn't work
$("#testing-div").append("NO, it was only Overriden in the 'test' Object.  It did not effect all the other new objects. :)" + "");
$("#testing-div").append("----------------------------------------------------" + "");


<meta charset="ISO-8859-1">
<title>Module Test</title>

    <h1>This is a test for separate Modules and Private variables.</h1>
    <div id="testing-div">
    <script src=""></script>
    <script src="main.js"></script>

This is what is displayed on the web page after you run the above code.

This is a test for separate Modules and Private variables.

This first part shows what does not work; everything is 'undefined'. 
You are unable to access the var or func directly. 
MODULE.privateParent = undefined = undefined
MODULE.sub.childMessage = undefined
MODULE.sub.Constr = undefined
MODULE.sub.childFunction = undefined
END lesson. You must access childFunction() through the new operator.
Let's see if making an instance of the Object works
- trying to access parent private field: parentPrivate
- trying to access parent private field: parentPrivate
Looks like it did!!!!
Now let's try to change the childFunction() ?
- This is a new function.
Looks like it was changed. :(
Does it stay changed?
- trying to access parent private field: parentPrivate
- trying to access parent private field: parentPrivate
NO, it was only Overriden in the 'test' Object. It did not effect all the other new objects. :)

If you want to use RequireJS to accomplish the above, you can.  RequireJS uses the Module Pattern which is what you and I are already using.  If you want to separate out the files then there are two ways to do this.

 1. Normal - Just set up your JS files to use RequireJS and drop in the above Modules with only a slight modification.
 2. Leveraged - Use the Module nature of RequireJS as the modules to set up the closures.  This looks like it may be harder to figure out but it may be more efficient in the long run.

NOTE: I haven't had a chance to compare these two options yet but wanted to include them for completeness.

You may also find the following references helpful:

 - JavaScript Module Pattern: In-Depth
 - Private Members in JavaScript

Friday, August 22, 2014

Java MVC 1.0

Why? Why not JSF? Why another MVC framework?

The Java community was polled about what new features they wanted to see in Java EE 8. While 61% of respondents answered "Yes" to the question as to whether we should provide MVC support alongside JSF, only 26% felt that they could identify an existing technology here. Most requesters want a formal Java MVC API that can compare to Spring MVC. The third phase of the poll looked at all the technologies that received 60% or more votes.  In that poll there were 13 areas and the MVC JSR ranked 5th. 

This JSR is in no way meant to take anything away from JSF. (In fact in the new JSF proposal they are planning on supporting the MVC JSR.) It is instead intended to provide an alternative implementation to the MVC pattern. JSF is a component based MVC framework, while this JSR is a request (action) based MVC framework. The main difference is that JSF allows very little fine-grained control over the generated HTML/CSS/JS, whereas this JSR will provide that detailed control. Both framework styles have their place and value but one is not the other. 

The MVC JSR proposal was just announced on the JAX-RS mailing list and will be led by Santiago Pericas-Geertsen and Manfred Riem from Oracle. 

I have been thinking about MVC for a while now. I had actually considered submitting my own proposal until I found out that Oracle already had one in the works. After comparing notes with Santiago and Manfred, we realized we could work together on it. One of the biggest reasons that I wanted to work on the MVC spec is that I have spent years working with Spring and Spring MVC. In fact, my current role at Red Hat is the Spring lead for JBoss.  I make sure that Spring works on JBoss/WildFly. Additionally I have worked with server-side frameworks like Struts and VRaptor and client-side frameworks like Backbone.js and Angular.jsThat is why it felt like a perfect fit for me.  

What is MVC, if you are still wondering? For those of you that are unfamiliar with this design pattern, here is a bit of an overview and some insight into what I hope we build.

The Model View Controller (MVC) design consists of three kinds of objects. The Model is the application or data object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input. Before the use of the MVC pattern, user interface designs tended to lump these objects together. For example, JSPs sometimes merge database code, page design code, and control flow code. In practice, we find that unless these concerns are separated, larger applications become difficult to maintain. MVC decouples these concerns to increase flexibility and reuse.

Frequently application developers implement the MVC pattern in applications themselves which is expensive and error prone. This specification aims to help developers create web applications that utilize the MVC architecture without reinventing the wheel. This shortens the development time of applications using the MVC pattern.

The decoupling of the View and the Model is done by establishing a notify protocol. A View must ensure that its appearance reflects the state of the Model. Whenever the Model’s data changes, the Model notifies Views that depend on it. In response, each View gets an opportunity to update itself. This approach lets multiple Views be attached to a Model to provide different presentations. New Views for a Model can be created without rewriting it.

Depending on context, users want to see the same basic Model information in different ways. Separating out the View from the Model and the Controller allows the development of multiple Views from the same Model. Most noticeably this could be providing the same Model to a rich client, a Web browser, a remote API, and a command-line interface. Even within a single Web interface you might have different customer pages at different points in an application.

After working with both server-side and client-side MVC frameworks; I have a simple goal. Make MVC easy to adopt and powerful enough to use. Many frameworks are cumbersome to learn, while others are too light weight to be of any real value. I am aiming at striking a balance between those two. 

Additionally, I will be able to make sure the MVC API is implemented on Red Hat JBoss (WildFly) in a timely fashion.