SlideShare a Scribd company logo
BUILDING MAINTAINABLE
JAVASCRIPT APPLICATIONS
JUAN 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 class
JavaScript 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 INHERITANCE
Java: 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 sam
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 POLYMORPHISM
Lets 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 = 3
var price = 17
var 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
LINE
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
}
}
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
code
Use JS capabilities
Less 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/bo
ok}
THANK
S!

More Related Content

What's hot

Java script
Java scriptJava script
Java script
Rajkiran Mummadi
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
Alaref Abushaala
 
Annotations in PHP: They Exist
Annotations in PHP: They ExistAnnotations in PHP: They Exist
Annotations in PHP: They Exist
Rafael Dohms
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal
 
Java script
Java scriptJava script
Java script
Sadeek Mohammed
 
Java script ppt
Java script pptJava script ppt
Java script
Java scriptJava script
Java script
Shyam Khant
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
Vishal Mittal
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
danwrong
 
Ant User Guide
Ant User GuideAnt User Guide
Ant User Guide
Muthuselvam RS
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Duckademy IT courses
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
Vijay Kalyan
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
Java script
Java scriptJava script
Java script
Soham Sengupta
 
Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator Alessio Ricco
 
Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)
Massimo Oliviero
 

What's hot (20)

Java script
Java scriptJava script
Java script
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Annotations in PHP: They Exist
Annotations in PHP: They ExistAnnotations in PHP: They Exist
Annotations in PHP: They Exist
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Java script
Java scriptJava script
Java script
 
Java script
Java scriptJava script
Java script
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Java script
Java scriptJava script
Java script
 
Js ppt
Js pptJs ppt
Js ppt
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
 
Ant User Guide
Ant User GuideAnt User Guide
Ant User Guide
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
Java script
Java scriptJava script
Java script
 
Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator
 
Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)
 

Viewers also liked

Mental health First Aid Certificate - Arif Wallani
Mental health First Aid Certificate  - Arif WallaniMental health First Aid Certificate  - Arif Wallani
Mental health First Aid Certificate - Arif WallaniArif Wallani
 
Event Promo Strategic Plan
Event Promo Strategic PlanEvent Promo Strategic Plan
Event Promo Strategic PlanAndrew Schneider
 
แฟ้มสะสมงาน878
แฟ้มสะสมงาน878แฟ้มสะสมงาน878
แฟ้มสะสมงาน878
จิตรลดา สุวรรณทิพย์
 
Cómo se busca en la web
Cómo se busca en la webCómo se busca en la web
Cómo se busca en la web
TICS & Partners
 
Comparative analysis of classical multi-objective evolutionary algorithms an...
 Comparative analysis of classical multi-objective evolutionary algorithms an... Comparative analysis of classical multi-objective evolutionary algorithms an...
Comparative analysis of classical multi-objective evolutionary algorithms an...
Javier Ferrer, PhD
 
Բլոգգինգի 15 ոճերը
Բլոգգինգի 15 ոճերըԲլոգգինգի 15 ոճերը
Բլոգգինգի 15 ոճերը
Artur Papyan
 
Property management business pla 2013 2016
Property management business pla 2013 2016Property management business pla 2013 2016
Property management business pla 2013 2016
mohamad aref mneimneh
 
Work Zone Traffic Mag't
Work Zone  Traffic Mag'tWork Zone  Traffic Mag't
Work Zone Traffic Mag'tSuresh Mondi
 
Tax E filing in pakistan
Tax  E filing in pakistan Tax  E filing in pakistan
Tax E filing in pakistan
Syed Jawwad-ACMA,APFA,CIE
 
Red Cross Certificate
Red Cross CertificateRed Cross Certificate
Red Cross CertificateGabriel Baez
 
Testing and symfony2
Testing and symfony2Testing and symfony2
Testing and symfony2
The Software House
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 

Viewers also liked (13)

Mental health First Aid Certificate - Arif Wallani
Mental health First Aid Certificate  - Arif WallaniMental health First Aid Certificate  - Arif Wallani
Mental health First Aid Certificate - Arif Wallani
 
Event Promo Strategic Plan
Event Promo Strategic PlanEvent Promo Strategic Plan
Event Promo Strategic Plan
 
แฟ้มสะสมงาน878
แฟ้มสะสมงาน878แฟ้มสะสมงาน878
แฟ้มสะสมงาน878
 
Cómo se busca en la web
Cómo se busca en la webCómo se busca en la web
Cómo se busca en la web
 
Comparative analysis of classical multi-objective evolutionary algorithms an...
 Comparative analysis of classical multi-objective evolutionary algorithms an... Comparative analysis of classical multi-objective evolutionary algorithms an...
Comparative analysis of classical multi-objective evolutionary algorithms an...
 
Բլոգգինգի 15 ոճերը
Բլոգգինգի 15 ոճերըԲլոգգինգի 15 ոճերը
Բլոգգինգի 15 ոճերը
 
Property management business pla 2013 2016
Property management business pla 2013 2016Property management business pla 2013 2016
Property management business pla 2013 2016
 
PROVISIONAL CERTIFICATE
PROVISIONAL CERTIFICATEPROVISIONAL CERTIFICATE
PROVISIONAL CERTIFICATE
 
Work Zone Traffic Mag't
Work Zone  Traffic Mag'tWork Zone  Traffic Mag't
Work Zone Traffic Mag't
 
Tax E filing in pakistan
Tax  E filing in pakistan Tax  E filing in pakistan
Tax E filing in pakistan
 
Red Cross Certificate
Red Cross CertificateRed Cross Certificate
Red Cross Certificate
 
Testing and symfony2
Testing and symfony2Testing and symfony2
Testing and symfony2
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 

Similar to Building maintainable javascript applications

"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
Jady Yang
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
rashmiisrani1
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
Roberto Suggi Liverani
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
GWTcon
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationAjax Experience 2009
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
Mike Pfaff
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Deggan Android Codestyle v1.0
Deggan Android Codestyle v1.0Deggan Android Codestyle v1.0
Deggan Android Codestyle v1.0
Fenton Martin
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags AdvancedAkramWaseem
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
Kazuhiro Sera
 
[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cooljavablend
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 

Similar to Building maintainable javascript applications (20)

"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Play framework
Play frameworkPlay framework
Play framework
 
Deggan Android Codestyle v1.0
Deggan Android Codestyle v1.0Deggan Android Codestyle v1.0
Deggan Android Codestyle v1.0
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
 

Recently uploaded

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 

Recently uploaded (20)

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 

Building maintainable javascript applications

  • 2.
  • 3. 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.
  • 4. …AND THE FUTURE IS CLOSER THAN YOU THINK! What do you think were the most popular programming languages ​​in GitHub on 2013?
  • 5. THAT SOUNDS VERY COOL BUT… PEOPLE HATE JAVASCRIPT!
  • 6. 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
  • 7. ... AND AS A RESULT, PEOPLE END UP WRITING SPAGHETTI CODE
  • 8.
  • 9. JAVASCRIPT ALLOWS CLASSES Java class JavaScript 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; }; }
  • 10. JAVASCRIPT ALLOWS CLASSES Java: instance of a class JavaScript: instance of a class
  • 11. JAVASCRIPT ALLOWS INHERITANCE Java inheritance JavaScript inheritance
  • 12. JAVASCRIPT ALLOWS INHERITANCE Java: 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 sam
  • 13. JAVASCRIPT ALLOWS NAMESPACES Java package JavaScript namespace
  • 14. JAVASCRIPT ALLOWS ENUMERATIONS Java enumeration JavaScript enumeration
  • 15. JAVASCRIPT ALLOWS ACCESS MODIFIERS Java: public and private access modifiersJavaScript: public and private access modifiers
  • 16. JAVASCRIPT ALLOWS POLYMORPHISM Lets to explain a classic example…
  • 17. THIS IS HOW WE IMPLEMENT POLYMORPHISM IN JAVA
  • 18. … AND THIS IS HOW WE IMPLEMENT POLYMORPHISM IN JAVASCRIPT
  • 19. 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}
  • 20. 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.
  • 21. 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}
  • 22. 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 */
  • 24. 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>
  • 25. BAD PRACTICES – MISSING SEMICOLONS Not using semicolons is a sin! var qty = 3 var price = 17 var total = qty * price Father, I don´t use semicolons!
  • 26. 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>
  • 27. BAD PRACTICES – CURLY BRACES IN NEW LINE 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 } } 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!
  • 28. 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 code Use JS capabilities Less code
  • 29. 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);
  • 31. 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.
  • 32. 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";
  • 33. 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;
  • 34. 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 || {};
  • 35. 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; };
  • 36. 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" };
  • 37. 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 }; }
  • 38. 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)
  • 40. 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}
  • 41. 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/bo ok}