detangling your javascript

Post on 29-Nov-2014

2.446 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

This is an introduction to refactoring techniques for JavaScript code that works but is legacy, poorly written or otherwise "tangled."

TRANSCRIPT

Detangling YourJavaScript

An Intro to JS Refactoring

Chris PowersConsultant with //obtiva

http://obtiva.com@chrisjpowers

3 Kinds of People Deal with Tangled Code

Consultants

New Hires

...and Everyone Else!

We all work with Tangled code on a

daily basis

What is “Tangled” JavaScript?

It is not BAD code!

Bad code doesn’t work.

Tangled code does work!

Tangled code will become “bad” code eventually because...

Tangled code is hard to read and understand.

Tangled code is hard to update and maintain.

Tangled code is easy to accidentally break.

“Tangled code is code based on lost

requirements.”

- Noel Rappin

Got Tangled Code?Do you...

Option #1:Big Bang Rewrite

Option #2:Detangle (Refactor)

ALWAYS Detangle!NEVER Rewrite!

Rewrites are tempting

Coders want to Code!

Writing codeis easier than reading code.

You CANNOT rewrite code you don’t

understand.

Your rewrite will likely miss requirements

In your client’s eyes, your rewrite will be

worse than the original.

What is Refactoring?

Methodically improving code quality without

altering behavior.

Making your complex code simple.

Simple code is...

#1Tested

#2Reveals Intent

#3DRY - Each piece of knowledge exists in

only one place

#4Small

Let’s Start Detangling...

First Things First:Set a Goal

How much code needs to be refactored?

How deeply?

Write a Test!

Why write tests?

Makes the code simple

Ensures BehaviorDoes Not Change

Forces Developer to Understand

Requirements

Refactoring #1Name the Anonymous

Functions

Refactoring #2Document

Responsibilities with Comments

Refactoring #3Extract Methods

Refactoring #4Improve Variable

Names

Refactoring #5Add Local Vars to Improve Legibility

Keep Extracting Functions

Refactoring #6Add Clarity with Underscore.js

Refactoring #7Isolate Display Logic

Refactoring #8Isolate DOM Manipulation

Refactoring #9Hide “Private”

Methods in Closures

Refactoring #10Scope Public Methods

in Namespaces

Refactoring #11Use Tiered

Sub-Namespaces

Refactoring #12Extend Namespaces(Don’t Overwrite)

Refactoring #13DRY Up Namespace

Initialization

Resources

http://javascriptmasters.com

Signup Code: ccc2011

ccc2011

Got questions?@chrisjpowers

top related