maintainable javascript

33
Maintainable JavaScript Nicholas C. Zakas S r. F rontend E ngineer, M y Yahoo!

Upload: nicholas-zakas

Post on 15-Jan-2015

13.589 views

Category:

Technology


1 download

DESCRIPTION

Explains how to write JavaScript in a way that creates the most value for your company, making it maintainable.

TRANSCRIPT

Page 1: Maintainable JavaScript

Maintainable JavaS cript

Nicholas C. ZakasS r. Frontend Engineer, My

Yahoo!

Page 2: Maintainable JavaScript

Why?

Writing New Code

Maintaining Code

Page 3: Maintainable JavaScript

Who cares?

• Your employer• Your co-workers, present and future• Development community

Page 4: Maintainable JavaScript

What is maintainability?

• Understandable• Intuitive• Adaptable• Extendable• Debuggable

Page 5: Maintainable JavaScript

Code ConventionsMaintainable JavaS cript

Page 6: Maintainable JavaScript

Readable code

• Indent your code• Comment your code

– Each method– Large sections of code– Difficult-to-understand algorithms– Hacks

Page 7: Maintainable JavaScript

Naming• Use logical names for variables and

functions– Don’t worry about length

• Variable names should be nouns (i.e., car)• Function names should begin with a verb

(i.e., getName())– For functions returning Boolean values, prefix

with “is”, such as isValid()• Avoid useless names such as foo, bar, temp

Page 8: Maintainable JavaScript

Indicate variable type

• Initializationvar found = false;

• Hungarian Notationvar sName = "Nicholas";

• Type Commentsvar cost /*:float*/ = 5.23;

Page 9: Maintainable JavaScript

Loose CouplingMaintainable JavaS cript

Page 10: Maintainable JavaScript

Client-s ide Layers

Behavior(JavaScript)

Presentation(CSS)

Structure(HTML)

Page 11: Maintainable JavaScript

S eparate HTML and JavaS cript

• JavaS cript in HTML<a onclick="sayHi()">text</a>

• HTML in JavaS criptelement.innerHTML = "<div>"

+ "<a href="/js/">text</a></div>";

Page 12: Maintainable JavaScript

S eparate CS S and JavaS cript

• JavaS cript in CS Sdiv.hd {

width: expression(ref.offsetWidth+"px"); }

• CS S in JavaS criptelement.style.color = "red";

Page 13: Maintainable JavaScript

Event handlers handle events

function handleKeyPress(event){ if (event.keyCode == 13){ var value = 5 * parseInt(txt.value); div.innerHTML = value; alert("Updated"); }}

Page 14: Maintainable JavaScript

Event handlers handle events

function handleKeyPress(event){ if (event.keyCode == 13){ performCalculation(); updateUI(); }}

Page 15: Maintainable JavaScript

Programming PracticesMaintainable JavaS cript

Page 16: Maintainable JavaScript

Don’t Modify Objects You Don’t Own

• Don’t add methods• Don’t override methods

• You don’t own Object, Array, RegExp, S tring, Number, Boolean, Date, Function

Page 17: Maintainable JavaScript

Avoid globals

• All publicly-accessible functions/variables should be attached to an object

• Namespace your objects– Don’t go overboard– Three levels is enough

YAHOO.Way.Too.Long.Namespace

Page 18: Maintainable JavaScript

Don’t overuse popular techniques

• Closures/nested functions– Use sparingly

• Object literals– S ingletons– Pass data

Page 19: Maintainable JavaScript

Throw your own errors

function add5(value) { if (arguments.length < 1) { throw new Error("add5: Not enough args"); }

return value + 5;}

Page 20: Maintainable JavaScript

Avoid null comparisons

function sortArray(value) { if (value != null) { value.sort(); }}

Page 21: Maintainable JavaScript

Avoid null comparisons

function sortArray(value) { if (value instanceof Array) { value.sort(); }}

Page 22: Maintainable JavaScript

Avoid null comparisons

function sortArray(value) { if (value instanceof Array) { value.sort(); } else { throw new Error("sortArray: argument must be an array.");

}}

Page 23: Maintainable JavaScript

Avoid null comparisons

• Use instanceof for specific types of objectsif (value instanceof constructor){

• Use typeof to test for string, number, Booleanif (typeof value == "string") {

Page 24: Maintainable JavaScript

Use Constants

function validate(value) { if (!value) { alert("Invalid value"); location.href = "/errors/invalid.php"; }}

Page 25: Maintainable JavaScript

Use Constants

var Constants = { INVALID_MSG : "Invalid value", INVALID_URL : "/errors/invalid.php"};function validate(value) { if (!value) { alert(Constants.INVALID_MSG); location.href = Constants.INVALID_URL; }}

Page 26: Maintainable JavaScript

Use Constants

• Repeated unique values• UI strings• URLs• Any value that may change in the future

Page 27: Maintainable JavaScript

Build ProcessMaintainable JavaS cript

Page 28: Maintainable JavaScript

Build

Build Process

Source Files

Page 29: Maintainable JavaScript

Recommendations

• One object or object definition per file– Indicate dependencies

• Use a build step– Combine files in appropriate order– S trip comments/whitespace– Validate code

Page 30: Maintainable JavaScript

S ummaryMaintainable JavaS cript

Page 31: Maintainable JavaScript

S ummary

• Code Conventions• Loose Coupling• Programming Practices• Build Process

Page 32: Maintainable JavaScript

Questions and AnswersMaintainable JavaS cript

Page 33: Maintainable JavaScript

Etcetera

• My email: nzakas@ yahoo-inc.com• My blog: www.nczonline.net