building maintainable javascript applications

Post on 18-Jan-2017

397 Views

Category:

Software

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

BUILDING MAINTAINABLE JAVASCRIPT APPLICATIONSJUAN DAVID CUARTAS@JUANCUARTAS

BECAUSE JAVASCRIPT WILL BECOME THE DOMINANT PROGRAMMING LANGUAGE OF THE FUTURE…• JavaScript is de facto language in Web Browsers, where Java Applets, VBScript

and Adobe Flash become obsolete.• JavaScript is becoming a popular Server Programming Language after the

success of Node.js.• JavaScript will become de facto language to write multi-platform apps running on

mobile devices, and mobile devices will rule the world!• JavaScript is being used to write smart TV apps.• JavaScript is now adopted by GNOME and Windows 8 to write desktop

applications.

…AND THE FUTURE IS CLOSER THAN YOU THINK!

What do you think were the most popular programming languages in GitHub on 2013?

THAT SOUNDS VERY COOL BUT…PEOPLE HATE JAVASCRIPT!

IT IS BECAUSE JAVASCRIPT IS A MISUNDERSTOOD PROGRAMMING LANGUAGE…Some people think JavaScript is such a bad programming language because it doesn´t allow Object Oriented Programming features like:• Classes• Inheritance• Packages/Namespaces• Enumerations• Access Modifiers• Polymorphism • Exceptions

... AND AS A RESULT, PEOPLE END UP WRITING SPAGHETTI CODE

JAVASCRIPT ALLOWS CLASSES

Java classJavaScript class

public class Person { private String _name;

public Person(String name) { _name = name; }

public String getName() { return _name; };

@Override public String toString() { return "name: " + _name; };}

function Person(name) { var _name = name;

this.getName = function () { return _name; };

this.toString = function () { return "name: " + _name; };}

JAVASCRIPT ALLOWS CLASSES

Java: instance of a class JavaScript: instance of a class

JAVASCRIPT ALLOWS INHERITANCE

Java inheritance JavaScript inheritance

JAVASCRIPT ALLOWS INHERITANCEJava: instance of an inherited class

JavaScript: instance of an inherited class

For both objects, it is invoked toString() method defined in “Person” parent class, having the same result.

JAVASCRIPT ALLOWS NAMESPACES

Java package JavaScript namespace

JAVASCRIPT ALLOWS ENUMERATIONS

Java enumeration JavaScript enumeration

JAVASCRIPT ALLOWS ACCESS MODIFIERS

Java: public and private access modifiersJavaScript: public and private access modifiers

JAVASCRIPT ALLOWS POLYMORPHISMLets to explain a classic example…

THIS IS HOW WE IMPLEMENT POLYMORPHISM IN JAVA

… AND THIS IS HOW WE IMPLEMENT POLYMORPHISM IN JAVASCRIPT

JSDOC

JSDoc is a markup language used to annotate JavaScript source code files, similar to Javadoc.

All files, classes, methods and properties should be documented with JSDoc with the appropriate tags and types.

For more reference see: {@link http://usejsdoc.org}

JSDOC - TAGS@access Specifies the access level of a member: private, protected, public.@author Identifies the author of an item.@callback Documents a callback function.@class Marks a function as a class.@constant {type} Marks an object as a constant.@copyright Documents some copyright information.@default Documents a default value.@enum {type} Marks an object as an enumeration.@extends Indicates that a class inherits from another class.@file Provides a description for a file.@ignore Removes a JSDoc item from the final output.@link Links to a JSDoc namepath or an external URL.@module Documents a JavaScript module.@namespace Marks an object as a namespace.@param {type} Documents a parameter of a function.@requires Describes a required module.@return {type} Documents the return value of a function.@type {type} Documents the type of an object.@version Documents the version number of an item.

JSDOC - TYPES- Primitive types: {boolean}, {number}, {string}- Instance types: {myNamespace.MyClass}, {{a: type, b: type>}}, {type[]}- Functions: {function(a: type, b: type): type}- Nullable types: {?type}- Variable args: {...type}

JSDOC - EXAMPLE/** * @file Here goes file description. Filenames should be all lowercase in * order to avoid confusion on case-sensitive platforms. * * @version 1.0 * @author Juan Cuartas <me@juancuartas.com> * @copyright Juan Cuartas, 2013 * * @requires some/module */

JAVASCRIPT BAD PRACTICES

BAD PRACTICES – GLOBAL VARIABLES

Bad practice:“items” is attached to the Window object. Any other function can easily override that variable.

Good practice:“items” is attached to a custom namespace.

<script>

var items = [];

function addToCart(item) { items.push(item); }

</script>

<script>

var shoppingCart = shoppingCart || {}; shoppingCart.items = [];

function addToCart(item) { shoppingCart.items.push(item); }

</script>

BAD PRACTICES – MISSING SEMICOLONS

Not using semicolons is a sin!

var qty = 3var price = 17var total = qty * price

Father, I don´t use

semicolons!

BAD PRACTICES – NO STRICT COMPARISION

Bad practice:This comparition performs coercion, so "1" == 1 is true!

Good practice

<script>

if (numericVar == 1) { // Statements... }

if (numericVar != 1) { // Statements... }

</script>

<script>

if (numericVar === 1) { // Statements... }

if (numericVar !== 1) { // Statements... }

</script>

BAD PRACTICES – CURLY BRACES IN NEW LINEfunction getTotal() {

var qty = 10; var price = 150; var total = qty * price;

return { qty: qty, price: price, total: total }}

function getTotal() { var qty = 10; var price = 150; var total = qty * price;

return { qty: qty, price: price, total: total }}

function getTotal() {

var qty = 10; var price = 150; var total = qty * price;

return; { qty: qty, price: price, total: total }}

WRONG!Because the JavaScript interpreter performs semicolon insertion, it thinks is missing a semicolon after the return statement, and the function doesn´t return anything at all.

Right style!

BAD PRACTICES – LOOPING OVER ARRAYS

Bad practice

var fruits = ["banana", "apple", "lemon", "grape"];

for (var i = 0; i < fruits.length; i++) {console.log(fruits[i]);

}var fruits = ["banana", "apple", "lemon", "grape"];

fruits.forEach(function (fruit) {console.log(fruit);

});

Good practice:More understandable codeUse JS capabilitiesLess code

BAD PRACTICES – INLINE EVENT HANDLERS

Bad practice:Attaching logic from the UI.

Good practice:Separate logic in a controller file.

<button id="btnSomething" onclick="doSomething();">

Click here...</button>

$("#btnSomething").click(doSomething);

JAVASCRIPT GUIDELINES

GUIDELINES - USE STRICT

<script>"use strict";hello = "Hello World!";alert(hello);</script>

<script>hello = "Hello World!";alert(hello);</script>

Always use "use strict" at the top of JS files. That allows to place a program, or a function, in a strict operating context, preventing certain actions from being taken and throws more exceptions with more information.

GUIDELINES - VARIABLES/** * Use lowerCamelCase for variable names. * * When you fail to specify var, the variable gets placed in the global context, * potentially clobbering existing values. Also, if there's no declaration, * it's hard to tell in what scope a variable lives (e.g., it could be in the * Document or Window just as easily as in the local scope). So always declare * with var. * * @type {string} */var someVariable = "Some value";

GUIDELINES - CONSTANTS/** * Use UPPER_CASE for constant names. Words should be separated through * underscore character. Always add the @const annotation. * * @const * @type {number} */var SOME_CONSTANT = 0;

GUIDELINES - NAMESPACES/** * Always prefix identifiers in the global scope with a unique pseudo namespace * related to the project or library. Use lowerCamelCase for namespaces. Always * add the @namespace annotation. * * @namespace */var namespace = namespace || {};

GUIDELINES - FUNCTIONS/** * Use lowerCamelCase for function names. * * @param {number} arg - This is a description for "arg". * @return {number} If the function returns something, it must be specified. */namespace.someFunction = function ( arg ) { return arg + 1;};

GUIDELINES - ENUMERATIONS/** * Use UperCamelCase for enum names, and UPPER_CASE for item names. * Always add the @enum annotation following enum type. * * @enum {string} */var MyEnumeration = { ITEM_A: "A", ITEM_B: "B", ITEM_C: "C"};

GUIDELINES - CLASSES/** * Use UperCamelCase for class names. Always add the @class annotation. * @class */function MyClass() {

/** * Private attributes and methods should be named with a trailing underscore. * @type {number} */ var _attribute = 1;

/** * Returns a string that represents the current object. * @return {string} A string that represents the current object. */ var _toString = function () { return _attribute.toString(); };

return { attribute: _attribute, toString: _toString };}

GUIDELINES – BOOLEAN EXPRESSIONS/** * The following are all false in boolean expressions: * * - null * - undefined * - "" the empty string * - 0 the number */

/* USE */ if (x) /* INSTEAD OF */ if (x != null)

/* USE */ if (x) /* INSTEAD OF */ if (x != null && x != "")

/* USE */ if (array.length) /* INSTEAD OF */ if (array.length > 0)

FRAMEWORKS REVIEW

JAVASCRIPT: THE GOOD PARTS

• Is the Holy Book for JavaScript Programmers• Writen by Douglas Crockford in 2008• Best known for popularize JSON Notation• Creator of JSLint and JSON2.js

For more reference see: {@link http://crockford.com}

LEARNING JAVASCRIPT DESIGN PATTERNS

• Written by Addy Osmani in 2012• This book is targeted at professional developers wishing to improve

their knowledge of design patterns and how they can be applied to the JavaScript programming language.

For more reference see: {@link http://addyosmani.com/resources/essentialjsdesignpatterns/book}

THANKS!

top related