building maintainable javascript applications

42
BUILDING MAINTAINABLE JAVASCRIPT APPLICATIONS JUAN DAVID CUARTAS @JUANCUARTAS

Upload: equisodie

Post on 18-Jan-2017

397 views

Category:

Software


2 download

TRANSCRIPT

Page 1: Building maintainable javascript applications

BUILDING MAINTAINABLE JAVASCRIPT APPLICATIONSJUAN DAVID CUARTAS@JUANCUARTAS

Page 2: Building maintainable javascript applications
Page 3: Building maintainable javascript applications

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.

Page 4: Building maintainable javascript applications

…AND THE FUTURE IS CLOSER THAN YOU THINK!

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

Page 5: Building maintainable javascript applications

THAT SOUNDS VERY COOL BUT…PEOPLE HATE JAVASCRIPT!

Page 6: Building maintainable javascript applications

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

Page 7: Building maintainable javascript applications

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

Page 8: Building maintainable javascript applications
Page 9: Building maintainable javascript applications

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; };}

Page 10: Building maintainable javascript applications

JAVASCRIPT ALLOWS CLASSES

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

Page 11: Building maintainable javascript applications

JAVASCRIPT ALLOWS INHERITANCE

Java inheritance JavaScript inheritance

Page 12: Building maintainable javascript applications

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.

Page 13: Building maintainable javascript applications

JAVASCRIPT ALLOWS NAMESPACES

Java package JavaScript namespace

Page 14: Building maintainable javascript applications

JAVASCRIPT ALLOWS ENUMERATIONS

Java enumeration JavaScript enumeration

Page 15: Building maintainable javascript applications

JAVASCRIPT ALLOWS ACCESS MODIFIERS

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

Page 16: Building maintainable javascript applications

JAVASCRIPT ALLOWS POLYMORPHISMLets to explain a classic example…

Page 17: Building maintainable javascript applications

THIS IS HOW WE IMPLEMENT POLYMORPHISM IN JAVA

Page 18: Building maintainable javascript applications

… AND THIS IS HOW WE IMPLEMENT POLYMORPHISM IN JAVASCRIPT

Page 19: Building maintainable javascript applications

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}

Page 20: Building maintainable javascript applications

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.

Page 21: Building maintainable javascript applications

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}

Page 22: Building maintainable javascript applications

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 <[email protected]> * @copyright Juan Cuartas, 2013 * * @requires some/module */

Page 23: Building maintainable javascript applications

JAVASCRIPT BAD PRACTICES

Page 24: Building maintainable javascript applications

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>

Page 25: Building maintainable javascript applications

BAD PRACTICES – MISSING SEMICOLONS

Not using semicolons is a sin!

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

Father, I don´t use

semicolons!

Page 26: Building maintainable javascript applications

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>

Page 27: Building maintainable javascript applications

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!

Page 28: Building maintainable javascript applications

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

Page 29: Building maintainable javascript applications

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);

Page 30: Building maintainable javascript applications

JAVASCRIPT GUIDELINES

Page 31: Building maintainable javascript applications

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.

Page 32: Building maintainable javascript applications

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";

Page 33: Building maintainable javascript applications

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;

Page 34: Building maintainable javascript applications

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 || {};

Page 35: Building maintainable javascript applications

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;};

Page 36: Building maintainable javascript applications

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"};

Page 37: Building maintainable javascript applications

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 };}

Page 38: Building maintainable javascript applications

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)

Page 39: Building maintainable javascript applications

FRAMEWORKS REVIEW

Page 40: Building maintainable javascript applications

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}

Page 41: Building maintainable javascript applications

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}

Page 42: Building maintainable javascript applications

THANKS!