Wednesday, November 9, 2016

QUnit Parameterize plugin

I got my hands on QUnit tool for automatic unit testing and found that some of the plugins for it were obsolete. One example is QUnit Parameterize plugin, it was made for QUnit below 2.x versions. I reworked it using Aptana Studio with JSlint enabled and created my own solution: Parameterize Pull request
I also created SO discussion page which I also answered once I had solution here: http://stackoverflow.com/questions/39017452/cannot-use-parametrize-plugin-for-qunit/39103346#39103346

This is how a QUnit Parameterize test should look like, utilizing QUnit.module(moduleName, hooks) function where hooks object contains before(), beforeEach(), afterEach() and after() functions to cover test atomicity:



If you scroll at the middle part after the module() function you will see a statement qunit.cases.init([/* array of tests parameters */]).test("test name", function (params, assert) {/* your test code goes here */});

"cases" subobject of QUnit is created by Parameterize plugin and I made it to use init() function to set the array of parametric tests.

Params variable sent to the test function contains the parameters sent with each object of the array inside init([/* your test parameters here */]).

You can also add expected number of assertions in your test, and QUnit will check if the asked number of assertions are run. The test will be failure if not.

Also another useful feature, if you see, the matrices defined inside beforeEach() are added to the "this" object. This means the matrices are available inside the test callback function this "this" keyword, as I use it: this[params.matrixStubName]

Another useful thing I do is, I added the "t" parameter for each test containing the order number of the test, so when a test fails you can easiliy search it in your code.

Parameterize contains also sequential and combinatorial parametric tests. I however didn't have a need for those. Combinatorial can create combinations of parametric tests from two sets, and as for sequential, I think my test here in the example is already sequential test.

You may be asking how can I automate build process using  QUnit with Jenkins CI?

Well I used Karma JS test runner and it has plugins for QUnit and for Jenkins CI.
I was working on a project and created two configuration files for Karma JS, one for Jenkins and one for local test execution.

karma.conf.local.js
karma.conf.js

If you have a problem with a Jenkins build in hanging state but everything else seems good then you need to set "singleRun" to true in karma.conf.js. This will execute the tests once and it will stop the karma test runner. If it is set to false the build will hang forever :)))

You should configure Jenkins with Karma as in this guide.


Jenkins Build
Jenkins Build

Jenkins source code management
Jenkins source code management

Build environment
Build environment

No need to tell Jenkins to upload the node_modules folder, just install Node JS plugin for Jenkins and then in your build add the command "npm install". This will automaticall install all Node JS dependencies.

Also you may want the "karma start" shell command to trigger running of your unit tests.

Jenkins shell commands
Jenkins shell commands

Karma will export the tests using the JUnit reporter plugin and a post build action is required to export the tests in xml format. I had folder called test-reports and set post build action to "test-reports/**/*.xml"

QUnit Test reports in Jenkins
QUnit Test reports in Jenkins

Wednesday, February 24, 2016

"The Art of Unit Testing", second edition - Book Review

In this post I will share my thoughts on a book I read recently. It is called "The Art of Unit Testing with examples in C#", second edition written by Roy Osherove.
Relatively old, written in December, 2013 in aroung 300 pages, Roy manages to cover all aspects of Unit Testing. How to start, how to structure your tests, utilize testing frameworks like NSubstitute, use test runners like NUnit to automate the process of running the tests.
How to refactor your code to handle better with tests, a short introduction to Test Driven Development, what types of testing frameworks exist(constrained/unconstrained), techniques how to create fake objects (stubs/mocks) in order to simulate testing environment.
Of course he uses .NET/C# related tools but roughly all principles apply in the same way to other programming languages and testing frameworks.

Unit testing is part of Test Driven Development and it a very useful technique to make sure your code works as expected. You first write the test and make sure it fails when it should fail. Then write the code that does the application functionality and make sure the test passes when it should pass. Run all the available unit tests and if all pass continue with writing test for the next application feature. If some of them fail refactor or debug the application code you just wrote. The good thing about test driven development is that it enables you to understand what are you trying to do, twice. That means, you think of the new feature that the application has to have, write a test about a certain functionality and make sure the test fails when it should fail. And then again think of the application feature and write the code that makes the test pass when it should pass.

Test Driven Development lifecycle
Test Driven Development lifecycle
So what is a Unit Test? Some people think a unit test must test a single function/method inside a system. Well according to Roy Unit test is a test that tests a single unit of work. That means if you have a rather complex function that calculates just "return of investment" you would create a test that tests that unit of work i.e return of investment, though you could separate the function in several different functions.

The book is separated in 4 parts plus an appendix with short explanation of the tools mentioned in the book.
What is new in the book? The author says that RhinoMocks is dead and that you should avoid it. It uses old testing technique and you should use frameworks that use Arrange-Act-Assert rule. Those would be NSubstitute, Typemock, FakeItEasy and many more.
The book is written for people who code and it teaches best practices for unit testing. If you have never written a unit test you should read it from start to finish.

Properties of a good unit test
Properties of a good unit test
Unit test definition
Unit test definition

Chapters:
  1. The basics of Unit Testing. This chapter covers what is a unit test, difference between unit and integration testing, a simple unit test example with NUnit and C# and a short introduction to Test Driven Development. SUT(System Under Test) or CUT(Class Under Test). Manual tests are stupid and not reliable, therefore automate the process of testing with unit tests.
  2. A first unit test. Exploring unit test frameworks, writing your first test with NUnit, NUnit attributes. This chapter cover several useful testing attributes like TestFixture, Test, TestCase, Ignore, ExpectedException, SetUp, TeadDown, Category etc... Roy says that he does not use SetUp and TearDown anymore because they just impair readablity of the test file and probably always you can develop helper functions that initialize object instead of doing that before and after each test.  
  3. Using stubs to break dependencies. This chapter defines what is stub, how to refactor code to make it testable with a stub, overcomming encapsulation problems and best practices to use stubs with your code. So what is a stub? A stub is a piece of code that fakes a certain behavior and enables you to test your code against that fake object. If you were to use real objects to test certain functionality that would be an integration test. 
  4. Interaction testing using mock objects. Defining interaction testing, what are mock objects, difference between fakes, mocks and stubs, using mocks best practices. So what is a mock object? A mock object is a fake object that is used to simulate certain behavior and all the communication between this fake object and the class under test is recorded in the mock. The test passes if the communication went well.
  5. Isolation (mocking) frameworks. Understanding isolation frameworks, using NSubstitute to create stubs and mocks, avoiding common missuses of isolation frameworks. This chapter also covers Arrange-Act-Assert rule and advanced ways to to handle stubs and mock in unison
  6. Digging deeper into isolation frameworks. Constrained vs Unconstrained frameworks, how unconstrained profiler-based frameworks work, defining values of a good isolation frameworks. Roy divides testing frameworks into constrained and unconstrained. Constrained frameworks are those that can test only the code written in the same programming language as the frameworks i.e only the public space. Constrained frameworks cannot test private, sealed, static methods. You are bound to the same rules as the compiler of your application. Unconstratined methods can test everything including, static, private, sealed members of a class. They can do this because they run before the compilation of your program using lower level APIs. In .NET all unconstrained frameworks are all profiler based which means, they use unmanaged profiling APIs wrapped around the running instance of CLR(Common Language Runtime). Some famous frameworks are, Java: PowerMock, JMocikt, C#: Typemock Isolator, JustMock, C++: Isolator++, Hippo Mocks.
  7. Test hierachies and organisation. Running unit tests during automated nightly builds, using continuous integration for automated builds, organising tests in a solution, test class inheritance patterns. This chapter cover some important asspects of software development. A development team should always have CI script that starts build automation script and runs all the tests available before building the software. I would recommend Jenkins for CI and Ant/Maven for build automation. As with any other things in your project unit tests should also be part of your source code repository. Make sure you maintain them along developing the software. Each class should have one test class and all tests should be related to the class under test. You can also use class inheritance in your tests if you think you repeat yourself.  Also interfaces or abstract classes to confirm certain functionalty is in the test class. 
  8. The pillars of good unit tests. Writing trustworthy, maintainable and readable tests. So unit tests should test only one single unit of work. Avoid using logic inside tests. Tests should be isolated from each other i.e don't run test inside other test. Unit tests are not integration tests and should not be treated as such. If you want to know the most important properties of a unit test this is the chapter to read.
  9. Integrating unit testing into organization. Becomming an agent of change, implementing a change using bottom-up or top-down approcah. If you are an agent of change expect to get tough questions and prepare to answer them. In each company you will find followers and blockers of the change. Top down is from the boss down to employees and bottom-up is vice versa. People always accept changes hardly so instead of pushing your idea forcefully try to implement some new working process that will lead to this change i.e implementing unit testing in the company. Also always use code coverage tools to make sure your tests cover all the necessary functionality in the software.
  10. Working with legacy code. Common problems with legacy code, where to begin writing tests, helpful tool for working with legacy code. Roy recommends this book on working with legacy code. So legacy code is not a joke and implementing unit tests in old code is a serious bussines. You should begin writing tests according to some priority, which features of the system have biggest priority. Of course you can also subdivide this very important software feature into code parts divided by complexity and dependency level. There are two strategies, easy-first and hard-first. Easy-first strategy is good if you have a team of unskilled unit testers which will enable them to become more skilled in time. With easy-first you expect new features to get tested harder until the hardest features are covered with tests. Hard-first is more suitable if you have a team of skilled unit testers, and at first it takes lot of time to test new features but after the hardest parts are being tested the time to test new  feature drastically reduces. Some known tools are: JustMock, Typemock Isolator, JMockit, Vise, FitNesse, NDepend, Resharper, Simian and TeamCity
  11. Design and testabiltiy. Benefits from testability design goals, pros and cons on design for testablity, tackling hard-to-test design. Make methods virtual, use interfaces as superclasses, make classes non-sealed, avoid instantiating concrete classes inside methods with logic, avoid direct calls to static methods, prefer calls to instance methods that later call statics, avoid constructors and static constructors that do logic, separate singleton logic from singleton holders. How do you test sensitive IP or pieces of software you are not allowed to reverse engineer? Sometimes programming languages or application frameworks are designed for testabiltiy so no additional testing is required apart from the application logic. 
  12. Appendix, Tools and frameworks. All tools and frameworks mentioned in the book are covered here with a short explanation. There are isolation frameworks, test frameworks, test APIs, IoC containers, database testing, web testing, UI testing(desktop), thread-related testing, acceptance testing, BDD-style API frameworks.
Well since this book is very comprehensive and cover anything you might think of when writing your tests I give it 4.8/5. I would give 5/5 but first I want to put my new knowledge into use and see if it is useful.

I upload some useful screenshots on my tumblr blog: http://tunephp.tumblr.com/

Thanks for reading my review. Best regards, Vlado.

Friday, November 13, 2015

"Jenkins: The Definitive Guide" - Book Review

In this post I will express my thoughts on a book written for a specific but very useful tool called Jenkins CI. The book is called "Jenkins: The Definitive Guide"  written by John Ferguson Smart.
So what is Jenkins CI (Continuous Integration)? Jenkins is a tool created by Kohsuke Kawaguchi
and its main purpose is as stated to create environment for continuous integration of your software.

Jenkins is a Java based tool, a web aplication to be more specific. Runs on various operating systems and can be installed in various ways, from a system service to running it into Winstone , a servlet container tool. You can use Jenkins to automate building your software, generate documentation for it, run unit/integration/acceptance tests, publish test reports in HTML/PDF format and even upload files to remote server.
While building, errors can happen so good notification support in Jenkins is here to help you get notified when that happens. There is support for email/SMS/RSS/IRC/Instant Messaging notifications. Even special devices that blink red when build fails and green when succedes.
Jenkins has good support for build automation tools like Maven and Ant.
It has embeded support for SVN and support for Git/Mercurial and others trough plugins.
On the other hand, you can test network applications using distributed builds with JMeter and try various test environments using Multi-configuration builds.
You can run parametrized builds as well run code coverage and code quality tests.
There are ton of plugins built for specific cases and usage which you can easily download and use in your builds. You can also write your own Jenkins plugin.

Now something about the book.

 From the book preface:
"This book is aimed at relatively technical readers, though no prior experience with Continuous Integration is assumed. You may be new to Continuous Integration, and would like to learn about the benefits it can bring to your development team. Or, you might be using Jenkins or Hudson already, and want to discover how you can take your Continuous Integration infrastructure further.
Much of this book discusses Jenkins in the context of Java or JVM-related projects. Nevertheless, even if you are using another technology stack, this book should give you a good grounding in Continuous Integration with Jenkins. We discuss how to build projects using several non-Java technologies, including as Grails, Ruby on Rails and .NET. In addition, many topics, such as general configuration, notification, distributed builds and security are applicable no matter what language you are using."

Written in july/2011, in around 400 pages you will get hands on various parts of this powerful tool. My advice is to try and install Jenkins on your system and install or try things mentioned in the book. Various scenarious require various hardware and software so you will not have all the possibilites to try all of them. But at least you can download the plugins and check them shortly what they do. Some plugins are obsolete but I made a list of plugins I installed as test on my computer.
All in all the book gives a good grasp of all that might need you in your future project. Apart from some typos the book is a great read, and you should definitely spend some time with it. I give 4.5/5.It will be useful for year to come.

More about the chapters.
  1. Chapter 1: Introducing Jenkins. A short introduction what is and what it is used for. A short history how Jenkins came from Hudson. How to install and what is CI(Continuous Integration).
  2. Chapter 2:  Your first steps with Jenkins. Covers how to make working environment for Jenkins, installing JDK, Git, Github and Maven. Your first build job and running premade tests on it. Specificaly this project https://github.com/wakaleo/game-of-life. You will use some Jenkins plugins like Cobertura. I tried it and it is buggy. I recommend using Jacoco instead. Here are the plugins used in this chapter: Git plugin, GitHub plugin, Coberturra plugin,Jacoco plugin.
  3. Chapter 3: Installing Jenkins. Covers how to install, possible ways how to install o different OS systems. Jenkins home directory, memory considerations, java/maven/ant options etc... Upgrading, backing up jenkins etc...
  4. Chapter 4: Configurin your Jenkins server. Adding JDK/Maven/Ant installations. Configuring global properties, mail server, reverse proxy etc...
  5. Chapter 5: Setting up your build jobs. Covers types of builds, like free style job or mave build job. How to configure source code management tools like SVN and Git trough Git/GitHub plugins. Build triggers, polling the SCM, or calling a hook script to start the build process. Build steps, post build steps, and other useful plugins. Plugins mentioned:
    Gerrit Trigger plugin, Groovy, Gradle, Grails, Jython, MSBuild, Phing, Phyton, Rake, Ruby, Artifactory plugin, Nexus plugin, NUnit plugin, NAnt plugin
  6. Chapter 6: Automated Testing. Automatin Unit  and Acceptance tests. Configuring test reports, code coverage, automated preformance testing with JMeter. Plugins mentioned: Clover, NCover, Emma, HTML Publisher plugin, JMeter plugin, Performance plugin
  7. Chapter 7: Securing Jenkins. Activating security. Using simple security or security with LDAP server. Then using Active Directory or Unix users and groups. Atlassian Crowd commercial tool. Authorization, who can do what with matrix based security or with project based matrix security. There is even a tool for enabling Role based security with a plugin. Auditing, keeping track of user actions. Plugins mentioned: LDAP Plugin, Active Directory plugin, Crowd plugin, Role Strategy plugin, Audit Trail plugin, Job Configuration History plugin.
  8. Capter 8: Notification. Email notification, claiming builds, instant messaging or IRC messaging. Desktop notifiers like Notifo, mobile/SMS notification, making noise with extreme feedback devices. Plugins mentioned: Email Extension plugin, Instant Messaging plugin, Jabber notifier plugin.
  9. Chapter 9: Code Quality. Code quality in your build process. Code quality tools like  PMD/CPD, FindBugs, Checkstyle, CodeNarc. Reporting code quality problems with Violations plugin. Reporting with SonarQube. Plugins mentioned: Violations plugin, FindBugs, PMD/CPD, Checkstyle, JDepend, NCover, CodeNarc, Sonar Gerrit Plugin, SonarQube plugin
    Coverage Complexity Scatter plugin, Static Analysis Utilities plugin, Task Scanner plugin.
  10. Chapter 10: Advanced builds. Parametrized builds and parametrized triggers. Multi-configuration build jobs. Parallel builds and build pipelines. Plugins mentioned: Build Promotion plugin, Maven Release Plugin, Copy Artifact plugin, promoted builds plugin, ArtifactPromotion plugin, Build Pipeline plugin, Parametrized Trigger plugin, Maven Jenkins plugin, Dependency Graph Viewer plugin, Locks and Latches plugin.
  11. Chapter 11: Distributed builds. Master/Slave strategies. Associating builds to slaves. Node monitoring and cloud computing. Plugins mentioned: Amazon EC2 plugin, CloudBees Docker Build and Publish plugin.
  12. Chapter 12: Automated Deployment and Continous delivery. Deployment script, database updates, smoke tests. Deploying Java or PHP/Ruby application. Plugins mentioned: Capitomcat plugin.
  13. Chapter 13: Maintaining Jenkins. Monitoring disk space and server load. Backing up configuration and Jenkins builds. Archiving and migrating build jobs. Plugins mentioned: Disk Usage plugin, Backup plugin, ThinBackup plugin, Monitoring plugin, Deploy plugin, Deploy WebSphere
  14. Appendix: Automating your Unit and Integration Tests. Automating your tests with Maven and Ant. 
I hope this post is useful. Best regards. Vlado

Monday, June 29, 2015

"Socket.IO Real-time Web Application Development" - book review

In this post I will share my thoughts on a book called "Socket.IO Real-time Web Application Development" written by Rohit Rai, published in 2013.
It has 6 chapters and 2 appendices in around 120 pages. This book is made for developers who want to start developing highly interactive and real-time web applications or multiplayer web based video games. The book starts with brief introduction to real-time server side of web applications. How it was and how it is now.
It then continues with building a simple chat application using NodeJS, ExpressJS, JQuery, Socket.IO and a templating engine called Jade. It is expected that the reader understands well JavaScript. Also NodeJS knowledge would be a plus but it is not necesarry as all needed aspects are well explained. 

Chapters:
  1. Going Real-Time on the Web. Covers history of XMLHTTPRequest, AJAX, FlashSocket, etc... and of course introduction to real-time web of today.
  2. Getting Started with Node.js. Covers brief introduction to Node.js programming. How to install it, how to import npm packages, and how to create a simple "hello world" application.
  3. Let's Chat. Explains how to start with Socket.IO on the server side but also on the client side. Some basic information what is what on the client/server and how it works.
  4.  Making it More Fun. This chapter is the longest one and I would recommend passing it in 2 or 3 parts with breaks between. It adds nicknames to chat users and "create rooms" functionality.
  5. The Socket.IO Protocol. Advantages od Socket.IO over WebSockets API. Socket.IO is much more capable and complex, therefore it needs dedicated protocol to function. It also covers all protocol types of messages that exist.
  6. Deploying and Scaling. Covers some information on how to keep your app on Node.js up and running and how to monitor background processes with Monit and Forever. Scaling with HAProxyNode Cluster and Redis.
  7. Appendix A: Socket.IO quick reference.
  8. Socket.IO Backends. Covers brief information about Socket.Io backends for Erlang, Google Go, Java, Perl and Python.
 The problems I faced while developing the sample chat application were:
  1. The book is made for Socket.IO version 0.9 which is discontinued and no longer available for download over npm. So I downloaded version 1.3.5.
  2. The protocol API is a bit different from version 0.9 to 1.3.5 so if you get deep into Socket.IO structure you'll be a bit confused.
  3. The web documentation is kind of poor so you will need to search the web for information how to get valuable data from the Socket.IO Server object.
My thoughts on the book, it is well made for what it was meant for, but the problem with these JS libraries is that they change very fast, so this book is getting old already. On the other hand it gives a good example to practice with newer versions of Socket.IO so therefore I recommend it for new Socket.IO developers.
There were some inconsistencies but all in all it serves its function. I give 4.2/5.

I uploaded the demo chat application on this location:
Its not finished, because I have other things to do at the moment, but it is good start. I used https://www.openshift.com/ with Node.js 0.10 with preinstalled HAProxy load balancer. 
If it is unavailable the service sets the app to idle state. So remind me or write an email if it stopped, to restart it.

Notes:
  •  Socket.IO creates a room for each tab you have on every browser. So if you have two tabs on Chrome and three tabs in Firefox connected to Socket.IO server, there will be 5 rooms generated for you inside the server state. 
  •  Socket.IO creates unique id for each socket connected to the server and that same id will be for a pregenerated room for the socket. You can create your room with custom name, and the socket you are using will be in two rooms, yours and the pregenerated one.
  •  Be careful how you connect to namespaces because the internal server state might get mess and you cannot get information properly. 
  • Socket.IO is easy to code. The API is same on both server and client.It works siemlesly though it is over HTTP layer.
Useful links I found on the web about Socket.IO:

https://github.com/SocketCluster/socketcluster
https://en.wikipedia.org/wiki/WebSocket
https://forums.openshift.com/keep-getting-program-node-serverjs-exited-with-code-8-and-503-service-unavailable
http://psitsmike.com/2011/10/node-js-and-socket-io-multiroom-chat-tutorial/
https://www.npmjs.com/package/roomdata
http://fzysqr.com/2011/02/28/nodechat-js-using-node-js-backbone-js-socket-io-and-redis-to-make-a-real-time-chat-app/
http://howtonode.org/websockets-socketio
http://coenraets.org/blog/2012/10/real-time-web-analytics-with-node-js-and-socket-io/
http://ejosh.co/de/2015/01/node-js-socket-io-and-redis-intermediate-tutorial-server-side/
https://en.wikipedia.org/wiki/Appserver.io

Thursday, February 26, 2015

How to structure you JS application

According to my reasearch which I was doing in past few months I got to some conclusions on how to structure your application for best code reusability.

Several patterns come to my mind, Module, Namespace, immediate functions, returning objects, using subobjects, using capitalized letters for functions/variables as "Constants", function scope and making accessor methods, JS constructors, using Yuidoc and Jasmine for better code quality.

Download the code from here: https://github.com/bluePlayer/practices/tree/master/AppStructure

Here is roughly what I am thinking about:

var externalJSLibrary = {},
    jquery = {},
    extJS = {},
    expressJS;

window.APP = window.APP || (function (wdo, lib1, lib2, lib3) {'use strict';
    var version = "1.0.0",
        config = {},
        parent = null,
        jqueryObj = lib1,
        extJSObj = lib2,
        expressJsObj = lib3,
        windowDocumentObject = wdo,
        MY_APP_NAME = "MyJSApplication",
        MY_EXCEPTION_MESSAGE = "My exception message",
        MY_APP_CONSTANT = "some message";

    return {
        Exceptions: {
            MyFirstException: function () {
                return {
                    message: MY_EXCEPTION_MESSAGE,
                    name: "MyFirstException"
                };
            }
        },

        Constants: {
            MY_APP_NAME: function () {
                return MY_APP_NAME;
            },
            MY_APP_CONSTANT: function () {
                return MY_APP_CONSTANT;
            }
        },

        Events: {
             keyDownEvent: function (event) {
                 // do some stuff when some key is pressed down on 'keydown' event.
             },

             keyUpEvent: function (event) {
                 // do some stuff when some key is released on 'keyup' event
             },

             keyPressEvent: function (event) {
                 // do some stuff when 'keypress' event was detected
             }
        },

        initApp: function (someObject, config) {
            var i;

            for (i in someObject) {
                if (someObject[i] !== null && typeof someObject[i] === 'object') {
                    if (someObject[i].hasOwnProperty('init')) {
                        someObject[i].init(config);
                    }
                    parent.initApp(someObject[i], config);
                }
            }
        },

        namespace: function (nsString, newObjectDefinition) {
            var parts = nsString.split('.'),
                helperObject = {},
                that = this,
                i = 0,
                field = {};

            if (parts[0] === that.Constants.MY_APP_NAME()) {
                parts = parts.slice(1);
            }

            for (i = 0; i < parts.length; i += 1) {
                if (that[parts[i]] === undefined) {
                    for (field in newObjectDefinition) {
                        if (newObjectDefinition.hasOwnProperty(field)) {
                            helperObject[field] = newObjectDefinition[field];
                        }
                    }
                    that[parts[i]] = helperObject;
                }
                that = that[parts[i]];
            }
            return that;
        },

        customFunction: function (a, b) {
            if (b < 0) {
                throw new parent.Exceptions.MyFirstException();
            } else {
                return 0;// do some stuff with a and b
            }
        },

        doSomeStuffWithJquery: function (someUrl) {
            jqueryObj.ajax({
                url: someUrl,
                xhrFields: {
                    withCredentials: true
                }
            });
        },

        doSomeStuffWithExtJS: function () {
            extJSObj.drawGraph();
        },

        doSomeStuffWithExpressJS: function () {
            expressJsObj.connectWithNodeJS();
        },

        init: function (configObject) {
            config = configObject;
            parent = this;
            parent.initApp(parent, config);
        }
    };
    }(window.document, jquery, extJS, expressJS));

window.APP.namespace('MySubObject', (function (lib) {'use strict';
    var config = {},
        parent = null,
        someLibrary = lib,
        MY_CONSTANT = "my constant",
        MY_EXCEPTION = "my exception";

    return {

        Exceptions: {
            MyNewException: function () {
                return {
                    message: MY_EXCEPTION,
                    name: "MyNewException"
                };
            }
        },

        Constants: {
            MY_CONSTANT: function () {
                return MY_CONSTANT;
            }
        },

        name: "MySubObject",

        myCustomFunction: function () {
            // do some stuff
        },

        init: function (configObj) {
            config = configObj;
            parent = this;
        }
    };
    }(externalJSLibrary)));

window.document.addEventListener("DOMContentLoaded", function (event) {'use strict';

    var myApp = window.APP;

    myApp.init({
        "event": event,
        otherConfig: {}
    });

    window.document.addEventListener('keydown', myApp.Events.keyDownEvent);
    window.document.addEventListener('keyup', myApp.Events.keyUpEvent);
    window.document.addEventListener('keypress', myApp.Events.keyPressEvent);

    });

"JavaScript Patterns" - book review

Hello. In this post I will share my thoughts on a book called "JavaScript Patterns" written by Stoyan Stefanov. Published in 2010 this book in about 210 pages covers the most important patterns that you can use in JavaScript to ease you work with this language. My guess is that this book is not for beginner JavaScript programmer, but you can always read this great book by Douglas Crockford, "JavaScript: The Good Parts" as an intro to JavaScript. These two books go hand in hand. Check my other book review here: http://tunephp.blogspot.com/2014/11/javascript-good-parts-book-review.html
If you really want to learn proper JS programming read both of them, first "JS the good parts" and then "JS Patterns" and try some programming practices in Firefox/Firebug.

The book has 8 chapters and has lot of useful code snippets you can use in building your brand new JavaScript application.

  1. Intruduction. Explains basic concepts of JS, like there are no classes in JS, everything is a object including, functions, arrays, objects etc... It also notes that you can use strict ("use strict", ECMAScript 5) mode, a modification of JS that removes some of the bad parts in JS. This chapter also introduces JSLint and the Console as debugging tools. You should always check your code with JSLint.
  2. Essentials. This chapter covers one of the main drawbacks in JS, and those are global variables. It also gives some tips how to avoid using too many globals, how to use "for", "for in" loops, avoiding implied typecasting with "==" sign, number conversions with parseInt() and parseFloat(), writing proper code, indentation, writing comments and using Yuidoc and JSLint.
  3. Literals and Contructors. It covers Object literal ({}) notation, JS constructors and naming convention for them and how to avoid problems using constructors. Array literals, check for "Arrayness" (arrays are objects in JS), working with JSON, regular expressions, primitive wrappers and throwing Errors/Exceptions.
  4. Functions. Covers function decalrations vs function expressions. Variable hoisting, function scope, function callbacks, returning functions, self defining functions, immediate functions and couple of useful tricks like memoization, curry, init-time branching etc... Probably the most important chapter in the book, you must not miss it as functions are the hearth of JavaScript.
  5. Object Creaing Patterns. Some object creating patterns like namespace patters(there is a very useful function for creating a tree of subobject, you can use it in your project.), private members, how to achieve real privacy in JS, Module pattern, Sandbox patterns, static members, JS "Constants", Chaining pattern etc... This chapter gives you better idea how to structure your code so that your project doesn't have trouble in the end.
  6. Code Reuse Patterns. Classical vs Prototypal inheritance patterns. You should avoid Class inheritance in JS since it is just a "syntaxic sugar", and always use Prototypal inheritance. This chapter also mentions some useful code reuse techniques, like borrowing methods, copying properties, some Class patterns etc...
  7. Design Patterns. This chapter covers how to code basic software engineering patterns in JavaScript, probably a chapter you don't want to miss. Singleton, Factory, Iterator, Decorator, Strategy, Facade, Proxy, Mediator and Observer. 
  8. DOM and Browser Patters. Covers some tools/concepts/patterns that can be used in a browser, like how to manipulate DOM tree, event handling, long running scripts, Ajax alikes, JSNOP, combining JS scripts, minifying, Loading techniques and preloading.
 So yes, this book cover very useful features of JavaScript and how to use them in browser. If you really want to become a web dev. this is the right book for you.

There are similarities with "JavaScript: The Good Parts" in the beginning, I felt like I was reading Doug's book again, but that is ok. It has lot of code and it is well explained so my grade for it is 4.5/5. Defineitely a book you should read.