SlideShare a Scribd company logo
1 of 54
Download to read offline
Professional
JavaScript

AntiPatterns
By

Mike Wilcox

February 2014
This code sucks!
if (target) {
if (target.targetParent.targetParent) {
target.targetParent.targetParent.targetParent = new Event(this);
} else {
target.targetParent.targetParent = new Event(this);
}
return target;
}
WTF??
this.graphs = utilities.settingArrayPropertyProxy(
settings.graphs,
function (index, newGraph) {
var currentLimits = chartEngine.getActualLimits(), newLimits;
chartEngine.addGraph(newGraph, index);
chartEngine.render();
},
function (newGraph, oldGraph) {
result = chartEngine.updateGraph(newGraph, oldGraph);
chartEngine.setLimits(self.xAxis().limits());
chartEngine.render();
},
function (index, removed) {
chartEngine.setLimits(self.xAxis().limits());
chartEngine.render();
},function (setting) {
return new Graph(self, chartEngine, setting);
},
false);
ilcox
ike W
M
Co m mitter!

HTML5
Graphic Design

JavaScript ES5

UI/UX architecture

CSS3
Works there.

Natch!
But more importantly...
Brend

an Eic
h

me

Knighted me
the
Noble Architect*

*not strictly true
What do I know??
Seriously…
Being a committer to the Dojo Toolkit JavaScript
library means not only having your code and
style scrutinized by know-it-all prima donnas,
open source experts, but your results also get
used by thousands of hacks that
expect magic developers who
expect quality code.
AntiMatter
In particle physics, antimatter is material composed of
antiparticles, which have the same mass as particles of
ordinary matter but have the opposite charge.

Encounters between particles and
antiparticles lead to the annihilation of both
AntiPattern
A commonly used process, structure or pattern of action
that despite initially appearing to be an appropriate and
effective response to a problem, typically has more bad
consequences than beneficial results.

Encounters
between patterns
and antipatterns
lead to the
annihilation of both
What to Expect
Discuss paradigms and patterns.
Good and bad.
Some patterns. Not all.

Focus on communications between
components.
Three words:
Maintainability, maintainability, maintainability
What is a Pattern?

Gang of Four

Addy Osmani

A design pattern is a general reusable solution
to a commonly occurring problem
Introduction
It is more difficult to build maintainable code in
JavaScript than languages such as Java or C# due to its
dynamic nature and its original intent to be a simple
language with little more to do than validate forms.
There is nothing built in to the language to assist in the
construction of large apps: no classes, no modules, no
packages.
There is little to no formal developer training in
JavaScript
The result of this is programmers attempt to solve
coding problems and end up with AntiPatterns
Hypothetical App
Let’s architect a chart application. The structure
and functionality should look like:
The Chart class is the API and main controller.
The Graph class controls the Axes and Series (which
draws the lines)
There can be multiple Graphs in a Chart.
There can be multiple Series in a Graph.
Chart App
Here are the main components of our hypothetical chart
app below. How do you think they should be wired up?

chart

engine

renderer

graph

x axis

y axis

series

layer

painter(s)
Chart App Structure
graph-proxy

series-proxy

e
re to hi d
Proxies ass below
the me

layer-proxy

chart

engine

renderer

graph

x axis

y axis

series

layer

painter(s)

An example of how circuitous the code path can get if the structure is not
carefully considered before hand.
Chart App Structure
When carefully considered, the code flow might look more like below.
It may take a little extra code to get to this, but it would be worth it
for a result that is easier to follow.

chart

engine

renderer

graph

x axis

y axis

series

layer

painter(s)
Code Flow
Meets acceptance criteria
Done!

Clean
Readable
Maintainable
Extensible
Testable

The quick way is often not the correct way
Causes of Bad
Architecture
Management AntiPatterns
Slave Driving Management
Sales Driven Development
Waterfall Development
Hiring Practices
Developer AntiPatterns
Not enough experience
The lack of working with others
Too much solo programming
Not enough collaboration
Just damn lazy
When you find a problem fix it, don't just drop a TODO

Super Star Programmers
Smart kids with no life that work 70 hours and generate layers
upon layers of code that works... but lacks best practices, code
reviews, comments, tests, and sometimes even reason
Code AntiPatterns
Procedural
Using nothing but functions is the very definition of
spaghetti code
jQuery encourages procedural… and $paghetti !
Good for a web "page", not good for a web "app"
If you’re not doing some sort of OOP, you will have
a massive climb toward a maintainable large
application
Easier for the developer to comprehend small
objects, rather than large routines
Spaghetti Object Oriented Programming
… or what I have dubbed: SOOP
Too much inheritance
Inheritance breaks encapsulation because the internals
of parent classes are visible to subclasses
Tends to counterintuitively create tight coupling
Makes for a very difficult-to-follow API when most of
the code is not in the current file
Making classes work together without stepping on
methods, etc gets complex
Even MOAH SOOP
FilteringSelect
MappedTextBox
ValidationTextBox
TextBox
_FormValueWidget
_FormWidget
_Widget
_TemplatedMixin
_CssStateMixin
_FormWidgetMixin
_FormValueMixin
_FormWidgetMixin
_TextBoxMixin
ComboBoxMixin
_HasDropDown
_FocusMixin
_WidgetBase
Stateful
Destroyable
_AutoCompleterMixin
SearchMixin

Over-inheritance is one
of the current problems
with Dojo

I needed to inspect this code for
what the server query should look
like. What file do you think that
was in?
MOAR SOOP
Inconsistent object methods
Violation of the Composition pattern
chart.setRect({}); graph.rect({});
settings.rect = {}; series.dimensions({});

Too much functionality
9000-line class files defeat the whole purpose of OOP

Lack of encapsulation
foo.bar.bop.hop.doThing();
Even worse for setting properties
Abstractions / Proxies
Don't do it. This ain't Java.
More overhead than direct coding, wasting precious
bytes
Because it is not native to the language, there is a
danger of creating an unmaintainable abstraction
Alternative:
Comment your damn code.
Smaller classes
Callbacks
Yes, callbacks can be an anti-pattern
Even simple callbacks as an argument is weak:
foo(x, onDone);

Passing a callback more than once quickly gets
messy
You may have heard of… callback hell.

Puts ownership of the callback in the wrong object,
which needs to check for existence
We have more modern techniques like Promises*

*Although most implementations suck
Getters and Setters
Not just an anti-pattern, getters and setters are EVIL!
Class = {
get x(){
this.node.style.left = x + ‘px’;
this.name = null;
delete this.age;
document.title = ‘My Crazy Page’;
}
};

Potential for crazy side effects
The DOM has it wrong
Private Properties

EVIL!

Can’t use the debugger to inspect objects
Can cause major problems in inheritance
Uses extra memory (in object instances)
Especially true in library code
Business code is less critical, but then… what are you
hiding, and from whom?
Suggest the underscore convention or an interface to
emphasize public API
http:/
/clubajax.org/javascript-private-variables-are-evil/
Properties

EVIL!

Now you may think I’ve gone off the rails. But...
In ref to setting from an external source

The state of a class should be handled by the class
If multiple objects are setting a property and
something goes wrong, you don’t know who dunnit
Settings objects and arrays may lose fields
Accessing a property may not be in sync with the
DOM, or necessitate overhead to keep them in sync
Okay, properties aren’t evil. But you should consider
MSDN Properties vs. Methods
when and how you use them.
Refactoring
Why Refactor
Doing things quick and dirty sets us up with a
technical debt, which is similar to a financial debt,
which incurs interest payments: the extra effort
to do in future development
All projects at some point need to pay down
technical debt
Eventually more time will be spent servicing the
debt than on increasing value
Accumulated technical debt becomes a major
disincentive to work on a project
Concepts courtesy of Jeff Atwood, Coding Horror
When to Refactor
Reasons we refactor:
It's been six months and you feel you are smarter now
You read about a cool pattern on Hacker News
You found a cool jQuery plugin that has some sweet
chaining
You want to completely rewrite the project because the
last dev used spaces instead of tabs

When your boss lets you refactor:
Never.
How to Refactor
Always Be Refactoring

ABR

As a project grows (and all projects grow) there will
be a continual need to refactor
For small refactors, do them as you go
For medium refactors, hide them in tasks
For large refactors, use git, work in a branch
Major rewrites should be done in chunks
Don’t panic, do a little at a time, even if meaningless
Reorganize
Run tests often
Solutions
require.js
You are using it, aren’t you?
Global namespaces are SO 2011
Globals can clash with other code, they are slow to
access, and they do not garbage collect
require.js provides a mini-framework, enforcing
packages, namespaces, and modules
Also consider:
Browserify - CommonJS
uRequire - UMD
Frameworks
Good for teams with less experience

Dojo
Ember
Angular
ExtJS
YUI
Marionette

But don’t get too excited.
Even with the

magical MVC pattern
frameworks will only get you
part way there.
Coupling
Tight
Content coupling
When one module modifies or relies
on the internal workings of another
module
Common coupling
When two modules share the same
global data
External coupling
When two modules share an
externally imposed data format,
communication protocol, or device
interface.
Control coupling
One module controlling the flow of
another, by passing it information

Loose
Data-structured coupling
When modules share a composite
data structure
Data coupling
When modules share data through,
for example, parameters. Each
datum is an elementary piece, and
these are the only data shared
Message coupling
Component communication is done
via parameters or message passing
No coupling
Modules do not communicate at all
with one another.
Encapsulation my boy...
Encapsulation is a form of data hiding; data, methods,
and properties. Only the interface or API is exposed.
The primary goal:
Easier for the developer to comprehend small
objects vs. large routines
But also:
Ownership of its own concepts, data, and
functionality
Breaks up functionality into smaller objects
It reduces the mystery of which module owns what
Proper Object Oriented Programming*
Object Composition: no internal details of composed
objects need be visible in the code using them
Two or three inheritance levels, or, very small
changes
Subclass Coupling
The child is connected to its parent, but the parent is
not connected to the child
For a child to talk to its parent violates a basic
programming principle of high and low level
functionality

*I have not consider any acronyms for this
TDD
Proper Test Driven Development means writing the tests
first - forcing you to consider the consequences before
you commit to them. You’ll find ways to:
Reduce dependencies
Encapsulate functionality
Create an intuitive interface
Keep the logic simple
Though multiple simple functions may be complex

The Failures of "Intro to TDD"
Naming and Arranging
Don't expect to cram it all into preconceived modelview-controller folders, it's too limiting, and the app
will grow out of it
Remember, the code path flows
down, not up, so the deeper modules
should not have access to root or
higher level modules
Business Logic
As much as possible, business logic should be as separate
from application logic, and especially the UI
Even if this means extra code is
needed to maintain the
separation

business
application
UI

low level functionality
Important Patterns
pubsub
Pros:
Library code is very simple
Can access distant areas of app
Cons:
Not guaranteed - pub can fire before sub is ready
Can be hard to follow code paths between unrelated modules
Over-use can lead to bad habits and sloppy code
Should only be used with very loosely coupled objects
! pubsub.publish('/module/loaded', {success:true});
! pubsub.subscribe('/module/loaded', function(object){
! ! console.log('load success:', object.success);
! });
Observables
Like events that you can set
Similar to event streams in that they fire on change,
and you can also read the current property
myName = obeservable('Mike');
console.log(myName); // Mike
obeservable('Bob');
console.log(myName); // Bob
myName.subscribe(function(value){
! if(value !== 'Mike'){
! ! console.log('Hey! My name is not ', value);
!}
});
Template Behaviors
<div id='menu' data-bind='ko.menu'></div>
ko.bind(‘#menu’, widgetWithMenu);

Attach DOM behavior to the template
Separates behavior from widget
Further decouples code
A good way to keep business logic separate from
DOM logic
Helps for unit testing
MVVM is a good TDD solution
Plugins
Use the concept for separating code
Various patterns for making a module pluggable
depends on code
Plugin may need intimate knowledge of host object
Importance is separation of concepts for
maintainability
Plugins aren't usually portable to other host objects
anyway
Event Emitters
The new hotness
Multiple connections can be made
Intent is clear - obvious they are events and what they do
Much better pattern than pubsub for objects that relate

dataLoader = {
! ! onDataLoaded: function(data){
! ! ! this.emit('dataloaded', data);
!! }
}
function onDataLoaded(data){
! ! console.log(data);
}
dataLoader.on('dataloaded', onDataLoaded);
Event Versatility
graph = {
! removeSeries: function(serieId){
! ! var serieData = this.serieMap[serieId].data.clone();
! ! this.serieMap[serieId].destroy();
! ! return serieData;
!}
}
chart = {
! removeSeries: function(seriesId){
! ! var graph = this.findSerieOwner();
! ! var seriesData = graph.removeSeries(seriesId);
! ! engine.removeSeriesData(seriesData);
! ! renderer.render();
Although this code is not bad, it is
!}
rigid. To operate on the series object,
};
access always needs to be through
chart.removeSeries(seriesId);
the top of the hierarchy: the chart.

Without the use of events, this logic
is necessary for methods to fire in
the correct order.
Event Versatility
series = {
! remove: function(){
! ! this.emit('remove-series', this);
this.destroy();
!}
};
graph = {
! on('remove-series', function(series){
! ! delete this.seriesMap[series.id];
! }, this);
};
chart = {
! on('remove-series', function(series){
! ! engine.removeSeriesData(series.data);
! ! renderer.render();
! }, this);
};
series = chart.getSeriesById(serieId);
series.remove();
series.isSelected(true);
series.addData([4,5,6]);

Here, remove() can be called directly
on the series, from anywhere inside
or outside of the chart, and events
will bubble up in the correct order.
This also makes sense semantically,
as series methods are called on the
series, and not the chart.
Conclusion
Refactor!
Always Be Refactoring

ABR

Little projects always become BIG projects
You will never have all the information up front
Sales can turn your app into Frankenstein
Practice defensive coding - build it knowing it will
change
Use best practices and your code will be maintainable and more enjoyable to work with
In spite of what you might think, you don’t have the
time to NOT do it right the first time
http:/
/www.slideshare.net/anm8tr
http:/
/www.meetup.com/Club-AJAX/
https:/
/twitter.com/clubajax

http:/
/clubajax.org/
Professional JavaScript: AntiPatterns

More Related Content

What's hot

GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademyGraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademyMarcinStachniuk
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishGrails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishSven Haiges
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
Expens-O-Meter, a web based tool built using Ruby on Rails
Expens-O-Meter, a web based tool built using Ruby on RailsExpens-O-Meter, a web based tool built using Ruby on Rails
Expens-O-Meter, a web based tool built using Ruby on Railsjatinder
 
Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13Stephan Hochdörfer
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJSTroy Miles
 
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)Joshua Warren
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryRefresh Events
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handlingMinh Hoang
 
Hotfixing iOS apps with Javascript
Hotfixing iOS apps with JavascriptHotfixing iOS apps with Javascript
Hotfixing iOS apps with JavascriptSergio Padrino Recio
 
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsDaniel McGhan
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - GreachHamletDRC
 
The Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember AppsThe Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember AppsJesse Cravens
 
Perl web programming
Perl web programmingPerl web programming
Perl web programmingJohnny Pork
 
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and BeyondWebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyondmguillem
 

What's hot (16)

GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademyGraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishGrails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Expens-O-Meter, a web based tool built using Ruby on Rails
Expens-O-Meter, a web based tool built using Ruby on RailsExpens-O-Meter, a web based tool built using Ruby on Rails
Expens-O-Meter, a web based tool built using Ruby on Rails
 
Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
 
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQuery
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handling
 
Hotfixing iOS apps with Javascript
Hotfixing iOS apps with JavascriptHotfixing iOS apps with Javascript
Hotfixing iOS apps with Javascript
 
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
The Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember AppsThe Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember Apps
 
Perl web programming
Perl web programmingPerl web programming
Perl web programming
 
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and BeyondWebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
 

Similar to Professional JavaScript: AntiPatterns

The 90-Day Startup with Google AppEngine for Java
The 90-Day Startup with Google AppEngine for JavaThe 90-Day Startup with Google AppEngine for Java
The 90-Day Startup with Google AppEngine for JavaDavid Chandler
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistMark Fayngersh
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..Mark Rackley
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Workshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfWorkshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfTobiasGoeschel
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4alexsaves
 
Backbone/Marionette introduction
Backbone/Marionette introductionBackbone/Marionette introduction
Backbone/Marionette introductionmatt-briggs
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
Introduction to Google App Engine with Python
Introduction to Google App Engine with PythonIntroduction to Google App Engine with Python
Introduction to Google App Engine with PythonBrian Lyttle
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Darwin Biler
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On RailsSteve Keener
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptAndrew Lovett-Barron
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesTikal Knowledge
 

Similar to Professional JavaScript: AntiPatterns (20)

The 90-Day Startup with Google AppEngine for Java
The 90-Day Startup with Google AppEngine for JavaThe 90-Day Startup with Google AppEngine for Java
The 90-Day Startup with Google AppEngine for Java
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwist
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Workshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfWorkshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdf
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4
 
10 Ways To Improve Your Code
10 Ways To Improve Your Code10 Ways To Improve Your Code
10 Ways To Improve Your Code
 
Backbone/Marionette introduction
Backbone/Marionette introductionBackbone/Marionette introduction
Backbone/Marionette introduction
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Fewd week4 slides
Fewd week4 slidesFewd week4 slides
Fewd week4 slides
 
Introduction to Google App Engine with Python
Introduction to Google App Engine with PythonIntroduction to Google App Engine with Python
Introduction to Google App Engine with Python
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On Rails
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate Javascript
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 

More from Mike Wilcox

Accessibility for Fun and Profit
Accessibility for Fun and ProfitAccessibility for Fun and Profit
Accessibility for Fun and ProfitMike Wilcox
 
Webpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need itWebpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need itMike Wilcox
 
Web Components v1
Web Components v1Web Components v1
Web Components v1Mike Wilcox
 
Great Responsive-ability Web Design
Great Responsive-ability Web DesignGreat Responsive-ability Web Design
Great Responsive-ability Web DesignMike Wilcox
 
Model View Madness
Model View MadnessModel View Madness
Model View MadnessMike Wilcox
 
Hardcore JavaScript – Write it Right
Hardcore JavaScript – Write it RightHardcore JavaScript – Write it Right
Hardcore JavaScript – Write it RightMike Wilcox
 
The Great Semicolon Debate
The Great Semicolon DebateThe Great Semicolon Debate
The Great Semicolon DebateMike Wilcox
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and HowMike Wilcox
 
Webpage Design Basics for Non-Designers
Webpage Design Basics for Non-DesignersWebpage Design Basics for Non-Designers
Webpage Design Basics for Non-DesignersMike Wilcox
 
Why You Need a Front End Developer
Why You Need a Front End DeveloperWhy You Need a Front End Developer
Why You Need a Front End DeveloperMike Wilcox
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About RESTMike Wilcox
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5Mike Wilcox
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5Mike Wilcox
 
How to get a Job as a Front End Developer
How to get a Job as a Front End DeveloperHow to get a Job as a Front End Developer
How to get a Job as a Front End DeveloperMike Wilcox
 
The History of HTML5
The History of HTML5The History of HTML5
The History of HTML5Mike Wilcox
 
Thats Not Flash?
Thats Not Flash?Thats Not Flash?
Thats Not Flash?Mike Wilcox
 

More from Mike Wilcox (20)

Accessibility for Fun and Profit
Accessibility for Fun and ProfitAccessibility for Fun and Profit
Accessibility for Fun and Profit
 
WTF R PWAs?
WTF R PWAs?WTF R PWAs?
WTF R PWAs?
 
Advanced React
Advanced ReactAdvanced React
Advanced React
 
Webpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need itWebpack: What it is, What it does, Whether you need it
Webpack: What it is, What it does, Whether you need it
 
Dangerous CSS
Dangerous CSSDangerous CSS
Dangerous CSS
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Great Responsive-ability Web Design
Great Responsive-ability Web DesignGreat Responsive-ability Web Design
Great Responsive-ability Web Design
 
Model View Madness
Model View MadnessModel View Madness
Model View Madness
 
Hardcore JavaScript – Write it Right
Hardcore JavaScript – Write it RightHardcore JavaScript – Write it Right
Hardcore JavaScript – Write it Right
 
The Great Semicolon Debate
The Great Semicolon DebateThe Great Semicolon Debate
The Great Semicolon Debate
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and How
 
Dojo & HTML5
Dojo & HTML5Dojo & HTML5
Dojo & HTML5
 
Webpage Design Basics for Non-Designers
Webpage Design Basics for Non-DesignersWebpage Design Basics for Non-Designers
Webpage Design Basics for Non-Designers
 
Why You Need a Front End Developer
Why You Need a Front End DeveloperWhy You Need a Front End Developer
Why You Need a Front End Developer
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About REST
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5
 
The Fight Over HTML5
The Fight Over HTML5The Fight Over HTML5
The Fight Over HTML5
 
How to get a Job as a Front End Developer
How to get a Job as a Front End DeveloperHow to get a Job as a Front End Developer
How to get a Job as a Front End Developer
 
The History of HTML5
The History of HTML5The History of HTML5
The History of HTML5
 
Thats Not Flash?
Thats Not Flash?Thats Not Flash?
Thats Not Flash?
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringWSO2
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityVictorSzoltysek
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 

Professional JavaScript: AntiPatterns

  • 2. This code sucks! if (target) { if (target.targetParent.targetParent) { target.targetParent.targetParent.targetParent = new Event(this); } else { target.targetParent.targetParent = new Event(this); } return target; }
  • 3. WTF?? this.graphs = utilities.settingArrayPropertyProxy( settings.graphs, function (index, newGraph) { var currentLimits = chartEngine.getActualLimits(), newLimits; chartEngine.addGraph(newGraph, index); chartEngine.render(); }, function (newGraph, oldGraph) { result = chartEngine.updateGraph(newGraph, oldGraph); chartEngine.setLimits(self.xAxis().limits()); chartEngine.render(); }, function (index, removed) { chartEngine.setLimits(self.xAxis().limits()); chartEngine.render(); },function (setting) { return new Graph(self, chartEngine, setting); }, false);
  • 4. ilcox ike W M Co m mitter! HTML5 Graphic Design JavaScript ES5 UI/UX architecture CSS3 Works there. Natch!
  • 5. But more importantly... Brend an Eic h me Knighted me the Noble Architect* *not strictly true
  • 6. What do I know?? Seriously… Being a committer to the Dojo Toolkit JavaScript library means not only having your code and style scrutinized by know-it-all prima donnas, open source experts, but your results also get used by thousands of hacks that expect magic developers who expect quality code.
  • 7. AntiMatter In particle physics, antimatter is material composed of antiparticles, which have the same mass as particles of ordinary matter but have the opposite charge. Encounters between particles and antiparticles lead to the annihilation of both
  • 8. AntiPattern A commonly used process, structure or pattern of action that despite initially appearing to be an appropriate and effective response to a problem, typically has more bad consequences than beneficial results. Encounters between patterns and antipatterns lead to the annihilation of both
  • 9. What to Expect Discuss paradigms and patterns. Good and bad. Some patterns. Not all. Focus on communications between components. Three words: Maintainability, maintainability, maintainability
  • 10. What is a Pattern? Gang of Four Addy Osmani A design pattern is a general reusable solution to a commonly occurring problem
  • 11. Introduction It is more difficult to build maintainable code in JavaScript than languages such as Java or C# due to its dynamic nature and its original intent to be a simple language with little more to do than validate forms. There is nothing built in to the language to assist in the construction of large apps: no classes, no modules, no packages. There is little to no formal developer training in JavaScript The result of this is programmers attempt to solve coding problems and end up with AntiPatterns
  • 12. Hypothetical App Let’s architect a chart application. The structure and functionality should look like: The Chart class is the API and main controller. The Graph class controls the Axes and Series (which draws the lines) There can be multiple Graphs in a Chart. There can be multiple Series in a Graph.
  • 13. Chart App Here are the main components of our hypothetical chart app below. How do you think they should be wired up? chart engine renderer graph x axis y axis series layer painter(s)
  • 14. Chart App Structure graph-proxy series-proxy e re to hi d Proxies ass below the me layer-proxy chart engine renderer graph x axis y axis series layer painter(s) An example of how circuitous the code path can get if the structure is not carefully considered before hand.
  • 15. Chart App Structure When carefully considered, the code flow might look more like below. It may take a little extra code to get to this, but it would be worth it for a result that is easier to follow. chart engine renderer graph x axis y axis series layer painter(s)
  • 16. Code Flow Meets acceptance criteria Done! Clean Readable Maintainable Extensible Testable The quick way is often not the correct way
  • 18. Management AntiPatterns Slave Driving Management Sales Driven Development Waterfall Development Hiring Practices
  • 19. Developer AntiPatterns Not enough experience The lack of working with others Too much solo programming Not enough collaboration Just damn lazy When you find a problem fix it, don't just drop a TODO Super Star Programmers Smart kids with no life that work 70 hours and generate layers upon layers of code that works... but lacks best practices, code reviews, comments, tests, and sometimes even reason
  • 21. Procedural Using nothing but functions is the very definition of spaghetti code jQuery encourages procedural… and $paghetti ! Good for a web "page", not good for a web "app" If you’re not doing some sort of OOP, you will have a massive climb toward a maintainable large application Easier for the developer to comprehend small objects, rather than large routines
  • 22. Spaghetti Object Oriented Programming … or what I have dubbed: SOOP Too much inheritance Inheritance breaks encapsulation because the internals of parent classes are visible to subclasses Tends to counterintuitively create tight coupling Makes for a very difficult-to-follow API when most of the code is not in the current file Making classes work together without stepping on methods, etc gets complex
  • 24. MOAR SOOP Inconsistent object methods Violation of the Composition pattern chart.setRect({}); graph.rect({}); settings.rect = {}; series.dimensions({}); Too much functionality 9000-line class files defeat the whole purpose of OOP Lack of encapsulation foo.bar.bop.hop.doThing(); Even worse for setting properties
  • 25. Abstractions / Proxies Don't do it. This ain't Java. More overhead than direct coding, wasting precious bytes Because it is not native to the language, there is a danger of creating an unmaintainable abstraction Alternative: Comment your damn code. Smaller classes
  • 26. Callbacks Yes, callbacks can be an anti-pattern Even simple callbacks as an argument is weak: foo(x, onDone); Passing a callback more than once quickly gets messy You may have heard of… callback hell. Puts ownership of the callback in the wrong object, which needs to check for existence We have more modern techniques like Promises* *Although most implementations suck
  • 27. Getters and Setters Not just an anti-pattern, getters and setters are EVIL! Class = { get x(){ this.node.style.left = x + ‘px’; this.name = null; delete this.age; document.title = ‘My Crazy Page’; } }; Potential for crazy side effects The DOM has it wrong
  • 28. Private Properties EVIL! Can’t use the debugger to inspect objects Can cause major problems in inheritance Uses extra memory (in object instances) Especially true in library code Business code is less critical, but then… what are you hiding, and from whom? Suggest the underscore convention or an interface to emphasize public API http:/ /clubajax.org/javascript-private-variables-are-evil/
  • 29. Properties EVIL! Now you may think I’ve gone off the rails. But... In ref to setting from an external source The state of a class should be handled by the class If multiple objects are setting a property and something goes wrong, you don’t know who dunnit Settings objects and arrays may lose fields Accessing a property may not be in sync with the DOM, or necessitate overhead to keep them in sync Okay, properties aren’t evil. But you should consider MSDN Properties vs. Methods when and how you use them.
  • 31. Why Refactor Doing things quick and dirty sets us up with a technical debt, which is similar to a financial debt, which incurs interest payments: the extra effort to do in future development All projects at some point need to pay down technical debt Eventually more time will be spent servicing the debt than on increasing value Accumulated technical debt becomes a major disincentive to work on a project Concepts courtesy of Jeff Atwood, Coding Horror
  • 32. When to Refactor Reasons we refactor: It's been six months and you feel you are smarter now You read about a cool pattern on Hacker News You found a cool jQuery plugin that has some sweet chaining You want to completely rewrite the project because the last dev used spaces instead of tabs When your boss lets you refactor: Never.
  • 33. How to Refactor Always Be Refactoring ABR As a project grows (and all projects grow) there will be a continual need to refactor For small refactors, do them as you go For medium refactors, hide them in tasks For large refactors, use git, work in a branch Major rewrites should be done in chunks Don’t panic, do a little at a time, even if meaningless Reorganize Run tests often
  • 35. require.js You are using it, aren’t you? Global namespaces are SO 2011 Globals can clash with other code, they are slow to access, and they do not garbage collect require.js provides a mini-framework, enforcing packages, namespaces, and modules Also consider: Browserify - CommonJS uRequire - UMD
  • 36. Frameworks Good for teams with less experience Dojo Ember Angular ExtJS YUI Marionette But don’t get too excited. Even with the magical MVC pattern frameworks will only get you part way there.
  • 37. Coupling Tight Content coupling When one module modifies or relies on the internal workings of another module Common coupling When two modules share the same global data External coupling When two modules share an externally imposed data format, communication protocol, or device interface. Control coupling One module controlling the flow of another, by passing it information Loose Data-structured coupling When modules share a composite data structure Data coupling When modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data shared Message coupling Component communication is done via parameters or message passing No coupling Modules do not communicate at all with one another.
  • 38. Encapsulation my boy... Encapsulation is a form of data hiding; data, methods, and properties. Only the interface or API is exposed. The primary goal: Easier for the developer to comprehend small objects vs. large routines But also: Ownership of its own concepts, data, and functionality Breaks up functionality into smaller objects It reduces the mystery of which module owns what
  • 39. Proper Object Oriented Programming* Object Composition: no internal details of composed objects need be visible in the code using them Two or three inheritance levels, or, very small changes Subclass Coupling The child is connected to its parent, but the parent is not connected to the child For a child to talk to its parent violates a basic programming principle of high and low level functionality *I have not consider any acronyms for this
  • 40. TDD Proper Test Driven Development means writing the tests first - forcing you to consider the consequences before you commit to them. You’ll find ways to: Reduce dependencies Encapsulate functionality Create an intuitive interface Keep the logic simple Though multiple simple functions may be complex The Failures of "Intro to TDD"
  • 41. Naming and Arranging Don't expect to cram it all into preconceived modelview-controller folders, it's too limiting, and the app will grow out of it Remember, the code path flows down, not up, so the deeper modules should not have access to root or higher level modules
  • 42. Business Logic As much as possible, business logic should be as separate from application logic, and especially the UI Even if this means extra code is needed to maintain the separation business application UI low level functionality
  • 44. pubsub Pros: Library code is very simple Can access distant areas of app Cons: Not guaranteed - pub can fire before sub is ready Can be hard to follow code paths between unrelated modules Over-use can lead to bad habits and sloppy code Should only be used with very loosely coupled objects ! pubsub.publish('/module/loaded', {success:true}); ! pubsub.subscribe('/module/loaded', function(object){ ! ! console.log('load success:', object.success); ! });
  • 45. Observables Like events that you can set Similar to event streams in that they fire on change, and you can also read the current property myName = obeservable('Mike'); console.log(myName); // Mike obeservable('Bob'); console.log(myName); // Bob myName.subscribe(function(value){ ! if(value !== 'Mike'){ ! ! console.log('Hey! My name is not ', value); !} });
  • 46. Template Behaviors <div id='menu' data-bind='ko.menu'></div> ko.bind(‘#menu’, widgetWithMenu); Attach DOM behavior to the template Separates behavior from widget Further decouples code A good way to keep business logic separate from DOM logic Helps for unit testing MVVM is a good TDD solution
  • 47. Plugins Use the concept for separating code Various patterns for making a module pluggable depends on code Plugin may need intimate knowledge of host object Importance is separation of concepts for maintainability Plugins aren't usually portable to other host objects anyway
  • 48. Event Emitters The new hotness Multiple connections can be made Intent is clear - obvious they are events and what they do Much better pattern than pubsub for objects that relate dataLoader = { ! ! onDataLoaded: function(data){ ! ! ! this.emit('dataloaded', data); !! } } function onDataLoaded(data){ ! ! console.log(data); } dataLoader.on('dataloaded', onDataLoaded);
  • 49. Event Versatility graph = { ! removeSeries: function(serieId){ ! ! var serieData = this.serieMap[serieId].data.clone(); ! ! this.serieMap[serieId].destroy(); ! ! return serieData; !} } chart = { ! removeSeries: function(seriesId){ ! ! var graph = this.findSerieOwner(); ! ! var seriesData = graph.removeSeries(seriesId); ! ! engine.removeSeriesData(seriesData); ! ! renderer.render(); Although this code is not bad, it is !} rigid. To operate on the series object, }; access always needs to be through chart.removeSeries(seriesId); the top of the hierarchy: the chart. Without the use of events, this logic is necessary for methods to fire in the correct order.
  • 50. Event Versatility series = { ! remove: function(){ ! ! this.emit('remove-series', this); this.destroy(); !} }; graph = { ! on('remove-series', function(series){ ! ! delete this.seriesMap[series.id]; ! }, this); }; chart = { ! on('remove-series', function(series){ ! ! engine.removeSeriesData(series.data); ! ! renderer.render(); ! }, this); }; series = chart.getSeriesById(serieId); series.remove(); series.isSelected(true); series.addData([4,5,6]); Here, remove() can be called directly on the series, from anywhere inside or outside of the chart, and events will bubble up in the correct order. This also makes sense semantically, as series methods are called on the series, and not the chart.
  • 52. Refactor! Always Be Refactoring ABR Little projects always become BIG projects You will never have all the information up front Sales can turn your app into Frankenstein Practice defensive coding - build it knowing it will change Use best practices and your code will be maintainable and more enjoyable to work with In spite of what you might think, you don’t have the time to NOT do it right the first time