maintainable javascript

Post on 15-Jan-2015

13.589 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

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

TRANSCRIPT

Maintainable JavaS cript

Nicholas C. ZakasS r. Frontend Engineer, My

Yahoo!

Why?

Writing New Code

Maintaining Code

Who cares?

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

What is maintainability?

• Understandable• Intuitive• Adaptable• Extendable• Debuggable

Code ConventionsMaintainable JavaS cript

Readable code

• Indent your code• Comment your code

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

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

Indicate variable type

• Initializationvar found = false;

• Hungarian Notationvar sName = "Nicholas";

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

Loose CouplingMaintainable JavaS cript

Client-s ide Layers

Behavior(JavaScript)

Presentation(CSS)

Structure(HTML)

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

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

Event handlers handle events

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

Event handlers handle events

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

Programming PracticesMaintainable JavaS cript

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

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

Don’t overuse popular techniques

• Closures/nested functions– Use sparingly

• Object literals– S ingletons– Pass data

Throw your own errors

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

return value + 5;}

Avoid null comparisons

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

Avoid null comparisons

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

Avoid null comparisons

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

}}

Avoid null comparisons

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

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

Use Constants

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

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

Use Constants

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

Build ProcessMaintainable JavaS cript

Build

Build Process

Source Files

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

S ummaryMaintainable JavaS cript

S ummary

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

Questions and AnswersMaintainable JavaS cript

Etcetera

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

top related