freakin whitespace, building a javascript style guide

Post on 17-Jun-2015

431 Views

Category:

Software

3 Downloads

Preview:

Click to see full reader

DESCRIPTION

JavaScript Coding Conventions talk from the HTML5 Dev Conference, May 2014.

TRANSCRIPT

FREAKIN'WHITESPACE

Building a JavaScript Style Guide

LIZ LEE@lizlux

Front End Engineer @WikiaFront End Coding Conventions Team

MY GOALYou too, can have a style guide...

In less than 6 months!

"The social universe for fans by fans""Create your own wiki, we'll host it!"

AWESOMENESS:Open sourceCommunity driven400k+ wikias100M monthly uniquesRidiculous amounts of knowledge

CHALLENGES:Heavily customized MediaWikiScrappy startupGrowth:

2010: 40 Employees2014: 236 Employees600% in 4 years

Squeaky wheel...... gets to lead the JavaScript Coding Conventions group!

OUR MISSION

“ As a developer, I want a clear andwell documented guide covering codingconventions, patterns and best practicesfor JavaScript development at Wikia alongwith tools to help me in making my code

compliant.

KEY PRINCIPLES

#1: TRUST THE CODE

// bad$("#foo").addClass("active");$("#foo").width(200);$("#foo").click();

// bettervar $foo = $("#foo");$foo.addClass("active");$foo.width(200);$foo.click();

// best$("#foo").addClass("active") .width(200) .click();

CODE SMELLS"Any symptom in the source code of a program that possibly

indicates a deeper problem" -Wikipedia

SMELLSConditional complexityMix-matched white spaceLong methodsLong parameter listsDuplicate codeetc.

BROKEN WINDOWS EFFECTCrime begets crime

Smelly code begets smelly code

JQUERY OBJECT CACHING$("#foo").addClass("active");$("#foo").width(200);$("#foo").click();

// ...

$("#foo").css('color','blue'); // WTF?!$("#foo").text('derp!'); // >.<

"Fool me once..."

RULEZ!

https://github.com/Wikia/guidelines/blob/master/JavaScript/CodingConventions.md#caching-jquery-objects

MAX PARAMS// smelly!function makeImage(src, width, height, border, type, addedBy) { ... }

makeImages('myImage.gif', '', '', '', '', 'lizlux');

// much betterfunction makeImage(options) { ... }

makeImage({ src: 'myImage.gif', user: 'lizlux'});

RULEZ!

https://github.com/Wikia/guidelines/blob/master/JavaScript/CodingConventions.md#maximum-parameters

VAR "HOISTING"function foo() { bar(); var x = 1;}

// same asfunction foo() { var x; bar(); x = 1;}

Example:var foo = 1;function bar() { if (!foo) { var foo = 10; } alert(foo); // 10}bar();

var foo = 1;function bar() { var foo; // foo is undefined if (!foo) { foo = 10; } alert(foo); // 10}bar();

RULEZ!

https://github.com/Wikia/guidelines/blob/master/JavaScript/CodingConventions.md#variables

TRUST THE CODE

#2: DON'T REINVENT THEWHEEL

“ As a developer, I want a clear andwell documented guide covering codingconventions, patterns and best practicesfor JavaScript development at Wikia along

with tools to help me in making my codecompliant.

WHAT WE DID WRONG:Wrote all the rules

Then looked at the tools

FREAKIN' WHITESPACE!

WHITE SPACEWent with jQuery because why not?

Here's why not: eatPreztels( type );

"Function with a callback, object,or array as the last argumenthave no space after the lastargument"

- jQuery Style Guide

eatPretzels( type, function() { return 'Yum!';});

MEDIAWIKIeatDoughnuts( type, function() { return flavors['jelly'];} );

JSLINT

JSLINTCreated by Douglas Crockford, in 2002

“Discovered” JSON (created the spec)Author of JavaScript, The Good Parts

2002 - the wild west of JavaScriptMozilla 1.0NetscapeIE6

STYLE RULESStyle rules help us write easy to read, well documented, and

consistent code.

LANGUAGE RULESLanguage rules have an impact on functionality. They were

chosen based on performance implications and theirtendency to reduce bugs.

JSLINT STYLE RULESWhitespace set up to read like english:

Spaces go after commas and colons, not beforeSpaces after if while for and function as theywould in EnglishNo space between function name and invokingparentheses

BACKINTHEDAYTHEROMANSDIDNTUSESPACESORPUNCTUATIONANDMISUNDERSTANDINGSAROSESOTHEYHADTOINTRODUCETHESECONVENTIONSINTOTHEIRWRITING

BACKINTHEDAY THEROMANS DIDNTUSESPA CESOR PUNCTU ATIONANDMISUNDER STANDI NGSA ROSESOTHEYH ADTOINT RODUCETHESECONVE NTIONS INTOTHEIRWRITING

Back in the day, the romans didn't use spaces orpunctuation, and misunderstandings arose, so they had to

introduce these conventions into their writing.

LANGUAGE RULES

“ If there is a feature of a languagethat is sometimes problematic, and if it

can be replaced with another feature thatis more reliable, then always use the more

reliable feature.

~ Douglas Crockford

EQEQ "=="// Bad(foo == 0) // foo can be '', false, 0

// Good(foo === 0) // foo is 0

POPULAR CODING CONVENTION ONGITHUB

http://sideeffect.kr/popularconvention/#javascript

JSLINTCommonly usedIt worksNew employees might already be familiarCode quality tool compatibility

js-beautify: "jslint_happy"JSHint

#3: PROGRAMMERS ARE LAZYGood programmers are anyway!

TOOLSJSHintJS-BeautifyJSCS

It should be harder for us to fail than succeed.Run tools in pre-commit hooksIDE pluginsAuto-updating whitespace for legacy code (js-beautify)Code ClimatePlato

JSHINTCreated by Anton Kovalyov in 2010Fork of JSLintCommunity drivenMore configurable and forgiving than JSLint

“ Your sadly pathetic bleatings areharshing my mellow.

~ Douglas Crockford

“ That is insanely stupid code. I am notgoing to dumb down JSMin for this case.

~ Douglas Crockford

JSHINT

Config: .jshintrcIgnore line or file

JSHint.com

JS-BEAUTIFYUpdates whitespace for you.Developers are lazy!"jslint_happy"Config: .jsbeautifyrc

JSCSJavaScript Code SnifferEnforces whitespace and style rulesCompliments JSHintConfig: .jscs.jsonEx: "requireCurlyBraces" and"requireSpaceAfterKeywords"

CODE CLIMATE

CODE CLIMATE

PLATO

SCSS STYLE GUIDE

SCSS-LINTOpen source by Causes.comChecks stuff like:

Alphabetizing propertiesWhitespaceSelector depth

SMELLY CSS!

Duplicate Properties/* bad */h1 { margin: 10px; text-transform: uppercase; margin: 0; // Second declaration}

/* acceptable for handling browser support */.box { background: #fff; background: rgba(255, 255, 255, .5);}

Empty Rule/* bad */.cat {}

ID With Extraneous Selector/* bad */#submit-button.button { ...}

/* good */#submit-button { ...}

Over-specificity & Selector Depth/* bad - SCSS doesn't have to match the HTML structure! */.wrapper { .wrapper-inner { ul { li { a { .submit-button { ... } } } } }}.wrapper .wrapper-inner ul li a .submit-button { ... }

Sane Selector Depth/* good - only do what's necessary */.wrapper { .submit-button { ... }}

ANALYZE-CSSCreated by MacbreAnalyzes compiled css after preprocessors like SCSS andSASSChecks for duplicate rules due to mixinsGreat for analyzing large code bases

OTHER REFERENCEShttp://www.wikia.com/Abouthttp://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.htmlhttps://github.com/twbs/bootstrap/issues/3057#issuecomment-5135512https://www.youtube.com/watch?v=taaEzHI9xyYhttp://anton.kovalyov.net/p/why-jshint/

QUESTIONS?liz at lizlux dot net

@lizlux

top related