Java script best practices v4
-
Upload
thor-jorund-nydal -
Category
Software
-
view
78 -
download
2
description
Transcript of Java script best practices v4
JavaScript clean coding
Code integrity, readability and efficiency
Thor J. Nydal,Senior Software Consultant
Global variables
Declared in top scope:
var variableA = 0;
variableA = 0;
window.variableA = 0;
Problems of global variables
• May lead to unpredictable behaviour due to cross-module interference which is hard to cover through tests
• Use of global variables in subroutines is alsoimpeding performance
How to encapsulate variables
Solution to global variable issues:
/** anonymous closure, creates a virtual environment */(function() {
var data= {};function start() {}
})();
/** ECMA5 decl. singleton/namspace */var MyApp = {
data: {},start: function() {}
};
/** class decl. */var MyApp = function() {
var data = {};function _init() {}this.start = function() {}
};
Function declaration vs. expression
declaredFunction(); // will runfunction declaredFunction() {…
}
expressedFunction(); // runtime errorvar expressedFunction = function() {…
}
The problem with null in JavaScript
A JavaScript beginner will typically mix null and undefined:
(function() {…var car = CarRegister.getCar(id); // function normally returns a car object or
null, but in some situations also undefined
If (typeof car === ’object’) { // by checking that the result is an object, theprogrammer believes he is safe showCarInfo(car);
} else {showNotFoundMessage();
}})();
Handling null objects & undefined
Because getCar(…) also returns undefined, this is not enough:
If (car !== null) {showCarInfo(car);
}
The key here is to know that a null object is falsey and to extend the initial condition:
If (data && typeof data === ’object’) {// real object or array (not null and not undefined)
}
By habit, use strict comparision
var x = 1, y = ’1’;x == y // truex === y // false
var x , y = null;x == y // truex === y // false
var x = [’’, null, undefined];x == ’,,’ // truex === ’,,’ // false
Batch DOM interaction
Because the browser DOM and JavaScript engine runs seperately, and because of a performance bottleneck between the two, batch DOM operations should be batched to minimize browser reflow.
Use ECMA5 notation
Creating JS objects & arrays:
var object = new Object(); var object = {};
var array = new Array() var array = [];
Absolute programming principles?
The extent to how far YAGNI and DRY principles are pursued, is determined by the scope of the developement project in terms of software system strategy, lifetime etc.
However, there is never any good reason to describe anythingso it can be misunderstood. Therefore, the KISS prinsiple, which can be read as ”keep it simple and straightforward” is universal.
The SRP principle can also be seen as absolute for a professional programmer as there is never any good reasonto structure an app, regardless of size, in an unintuitive/unlogical way.
Use a templating/MVC framework
Provides:• Object check functions which handles both
undefined & null• By following its general outlines, you will be
helped to avoid creating global variables• An MVC framework will helps a programmer to
batch DOM operations more
Follow the JS application framework way to declaremodules and variables
Summary
• Be aware of the mentioned pitfalls of plain JavaScript, but learn theJS application framework used in your project with its utils so youcan focus on the business logics
• Make it a habit to use strict operators to make clearer code• Even if following an MVC framework, think transaction cost when
dealing with DOM operations and create better UI response at thesame time
• Developement and design principles are not neccesarrily absolute• Coding is an iterative process, even in the scope of deciding on how
to formulate a single variable – express yourself in a unambigiousgrounded way to reduce cross-cultural confusion and to indirectlyimprove team performance through more collaborative code
• Awareness and dicipline is required to follow mentioned guidelines
References
• Crockford, D. (2008) JavaScript: The Good Parts: The Good Parts. OReilly.
• Martin, R. (2008) Clean code: A handbook of agile software craftsmanship. Prentice Hall.