+ All Categories
Home > Technology > Blind faith and best practices mike behnke @localpcguy

Blind faith and best practices mike behnke @localpcguy

Date post: 02-Nov-2014
Category:
Upload: mike-behnke
View: 199 times
Download: 1 times
Share this document with a friend
Description:
Abstract: Stop using ==, you must use SASS, all your coding problems can be solved with Node.JS. So much advice and best practices, some of it from well-respected leaders in our web-dev community and much of it extremely dogmatic. So how do you filter out the noise and find a happy middle ground? How do you go about finding the best practices you should follow in a practical world where things are messy? This talk goes over some of the common front-end best practices and encourages engineers to not just blindly follow best practices, but understand the WHY behind them. Original slides (rendered with Reavel.JS) available here: http://lpg.io/best-practices About Mike Behnke: Mike Behnke is a website developer and software engineer, a tech geek, focused on front-end programming but also a bit dangerous on the server-side. He is a JavaScript and Android enthusiast. Mike Behnke works at Enlighten Agency (@EnlightenAgency) and tweets at @LocalPCGuy.
Popular Tags:
54
BLIND FAITH AND BEST PRACTICES Mike Behnke @localpcguy
Transcript
Page 1: Blind faith and best practices   mike behnke   @localpcguy

BLIND FAITH ANDBEST PRACTICES

Mike Behnke@localpcguy

Page 2: Blind faith and best practices   mike behnke   @localpcguy

STARTING OUT

Page 3: Blind faith and best practices   mike behnke   @localpcguy

PROGRAMMER'S JOURNEY

Page 4: Blind faith and best practices   mike behnke   @localpcguy

THERE MUST BE A BETTER WAYAt some point while learning, we've all come to this point, right?

Page 5: Blind faith and best practices   mike behnke   @localpcguy

ENTER...THE BEST PRACTICECommercial or professional procedures that are accepted or

prescribed as being correct or most effective.

Page 6: Blind faith and best practices   mike behnke   @localpcguy

BEST CODING PRACTICES==

a set of informal rules that the software development communityhas learned over time which can help improve the quality of

software.

Page 7: Blind faith and best practices   mike behnke   @localpcguy

MISGUIDED?

Most "Best Practices" in Software Engineering are there tokeep bad programmers from doing too much damage

The only "best practice" you should be using all the time is "UseYour Brain"

Page 8: Blind faith and best practices   mike behnke   @localpcguy

BLIND FAITH?==

a belief without true understanding,perception, or discrimination

Are Best Practices just blind faith inpeople that came before us

or that we deem smarter than us?

Page 9: Blind faith and best practices   mike behnke   @localpcguy

MY GOALTo encourage everyone to look at best practices and know WHY

they use the ones they do, and WHEN to discard ones that nolonger are effective.

Page 10: Blind faith and best practices   mike behnke   @localpcguy

AND TO ENCOURAGE BEST PRACTICES...BUTMake sure they really are, and know when to follow them

And when to ignore them

Page 11: Blind faith and best practices   mike behnke   @localpcguy

EXAMINATIONLet's take a look at some best practices

Some are obvious, others we'll talk about the why a bitmore

photo by Sara Cimino

Page 12: Blind faith and best practices   mike behnke   @localpcguy

HTML

Page 13: Blind faith and best practices   mike behnke   @localpcguy

SEMANTICS MATTERHelp screen readers, Google, and other

machines/bots parse meaning from markup<div class="header"> <ul class="nav"></ul></div><div class="body"></div><div class="footer"></div>

<!-- vs -->

<header> <nav></nav></header><section></section><footer></footer>

Page 14: Blind faith and best practices   mike behnke   @localpcguy

HTML5 SEMANTICS

Page 15: Blind faith and best practices   mike behnke   @localpcguy

EVERYTHING IN THE PROPER PLACEJavaScript: - just before body close - with exceptions for scripts like Modernizr - analytics?

CSS - in the head - prevents layout readjustment - before any JavaScript to prevent possible blocking

Page 16: Blind faith and best practices   mike behnke   @localpcguy

HTML5 BOILERPLATEGreat starting point."A professional front-end template for building fast, robust,and adaptable web apps or sites."Great reference guidePerformance - check out the various server configs

Page 17: Blind faith and best practices   mike behnke   @localpcguy

HTML5 BOILERPLATETHE CODE

<!doctype html><html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Place favicon.ico and apple-touch-icon(s) in the root directory -->

<link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.8.0.min.js"></script> </head> <body> <!--[if lt IE 8]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]-->

<!-- Add your site or application content here --> <p>Hello world! This is HTML5 Boilerplate.</p>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.min.js"><\/script>' <script src="js/plugins.js"></script> <script src="js/main.js"></script>

Page 18: Blind faith and best practices   mike behnke   @localpcguy

CSS

Page 19: Blind faith and best practices   mike behnke   @localpcguy

GENERAL RULESUse a reset (or normalize) style sheetAvoid browser hacks(use HTML Conditional Comments to set body classes for old IEs)

<!doctype html><!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--><!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--><!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--><!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->

Page 20: Blind faith and best practices   mike behnke   @localpcguy

CLEAN STYLESHEETSProvide Stylesheet information and indicate structure

/* stylesheet for Corp BarFile created date: 09.15.2010Last modified date: 06.04.2012By: [name]

For: [section]*/

/* Table of Contents- Typeography- Link Styles- Other sitewide styles- Actions- Layout- HEADER- TOP NAV- MAINCONTENT- FOOTER*/

(…later in the document…)/* =Layout */ (etc.)

Page 21: Blind faith and best practices   mike behnke   @localpcguy

SELECTORSAvoid IDs for styling - specificity problems, not reusableAs short as possible, reduce specificityUse shorthand properties when possible

/* Bad */#sidebar { background-color: #fff; background-image: (bg.png); background-position: 0 0; background-repeat: repeat-x; border-width: 1px; border-style: solid; border-color: #ffff00; font-family: Georgia, serif; font-size: 1.33em; line-height: 1.33em; font-weight: normal; margin: 10px 20px 10px 20px; padding: .1em;}

/* Better */.sidebar { background: #fff url(bg.png) repeat-x 0 0; border: 1px solid #ff0; font: normal 1.33em/1.33 Georgia, serif; margin: 10px 20px; padding: .1em;

Page 22: Blind faith and best practices   mike behnke   @localpcguy

MULTIPLE FILESPrefer multiple, smaller CSS files over a single monolithic file.

Concatenate and minify for performance

Page 23: Blind faith and best practices   mike behnke   @localpcguy

PREPROCESSORSQuickly becoming best practice to use a preprocessor

Adds to developer efficiencyReduces errorsPrevents repetitionCareful: Don't over-complicate thingsCareful: Don't over-nest selectors

Oh, which one, Sass, Less or Stylus? Flip a coin, drawstraws...or just base it on your framework

Page 24: Blind faith and best practices   mike behnke   @localpcguy

MODULARIZE YOUR CSS is a popular styleSMACSS

Make elements portable, reusableNo longer tied to a page or section

<div class="fldr fldr-callout"> <h2 class="fldr-name">Folder Name</h2> <span class="fldr-items">(32 items)</span></div>

Page 25: Blind faith and best practices   mike behnke   @localpcguy

FRAMEWORKSBootstrap and Foundation are very popular now

They are NOT best practices by themselves however

BUT THEY DO ENABLE BEST PRACTICES IN MANY CASES

Page 26: Blind faith and best practices   mike behnke   @localpcguy

JAVASCRIPT

Page 27: Blind faith and best practices   mike behnke   @localpcguy

EASY ONE? == VS ===All together now...

Know the difference, and use them appropriately

... wait, what? You thought it was always use ===?

// Use === when both type and value equality matter// or when inconsistent input may cause problemsif(1 === '1') //Returns falseif(1 == '1') //Returns true

if(0 === '') //Returns falseif(0 == '') //Returns true

// Use == when the types are predetermined and known// Or when it is more concise and clear than otherwiseif (typeof foo == 'undefined') // typeof always returns a stringif (foo.indexOf(bar) != -1) // indexOf always returns a numberif (foo != null) // more concise than checking null and undefined, but still clear

Page 28: Blind faith and best practices   mike behnke   @localpcguy

USE YOUR SEMICOLONS!var a = obj[a].forEach(logProp) // 'fail' : var a = obj[a].forEach(logProp)

Source - Ben Alman

Page 29: Blind faith and best practices   mike behnke   @localpcguy

ALWAYS USE CURLY BRACESGoto fail bug

hashOut.data = hashes + SSL_MD5_DIGEST_LEN;hashOut.length = SSL_SHA1_DIGEST_LEN;if ((err = SSLFreeBuffer(&hashCtx)) != 0) goto fail;if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0) goto fail;// ...if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) goto fail; goto fail; /* MISTAKE! THIS LINE SHOULD NOT BE HERE */if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0) goto fail;

err = sslRawVerify(...); /* SSL certs never fully verified */

Yes...this is C, not JavaScript...example was too good to pass up

Page 30: Blind faith and best practices   mike behnke   @localpcguy

BLOCKSOpening curly brace for blocks should go on the

same line as the declaration (in JavaScript)

function foo() { var bar = 1;

return // Oops! Return == undefined { bar: bar }}

Page 31: Blind faith and best practices   mike behnke   @localpcguy

SPACES AND TABS AND INDENTS,OH MY!

Use however many spaces per tab as you like

BUT FOLLOW YOUR COMPANY'S STANDARD(you do have a standard, right?)

Page 32: Blind faith and best practices   mike behnke   @localpcguy

JSLINT (OR HINT) YOUR CODECatch errors before you refresh.

SublimeLinter

Page 33: Blind faith and best practices   mike behnke   @localpcguy

USE STRICT(function(){ 'use strict'; name = 'Mike'; // Throws an error, no "var" var obj = { foo: true, foo: false }; // Error, duplicate property names}());

Catch potential errors quicker, no side effects for old browsers.[ref]

Prevents global variablesPrevents duplicate propertiesPrevents accidental function overwriteMakes eval (a bit) less evil

Page 34: Blind faith and best practices   mike behnke   @localpcguy

ENCAPSULATE YOUR CODE(function(){ // Do stuff here}());

Along with "use strict", keeps your variables from leaking into theglobal scope, makes your code more modular

Page 35: Blind faith and best practices   mike behnke   @localpcguy

USE THE MODULE PATTERNvar app = (function(){ 'use strict';

var settings;

return {

init: function(initialSettings) { settings = initialSettings; },

getOptions: function () { return settings.options; } };}());

Set a namespace, then expose just the parts ofyour module that you need exposed

History of and variety of examples and links to more readingJavaScript module patterns

Page 36: Blind faith and best practices   mike behnke   @localpcguy

JQUERY

Page 37: Blind faith and best practices   mike behnke   @localpcguy

STILL USE JQUERY?Makes the DOM tolerableOn a diet lately (only 32KB minified/gzipped)Cross-browser compatibility, events, ajaxPluginsTrusted by >50% of websites online

Page 38: Blind faith and best practices   mike behnke   @localpcguy

JQUERY IS JAVASCRIPTSo LEARN JavaScript first (at least )the basics

lpg.io/web-dev/javascript-resources

Page 39: Blind faith and best practices   mike behnke   @localpcguy

ISOLATE JQUERYPass jQuery into your module

(function ($, undefined) { // ... Do Stuff with $ // Now jQuery scoped locally to $}(jQuery));

Bonus: undefined really is undefined

Page 40: Blind faith and best practices   mike behnke   @localpcguy

JQUERY READYDon't put all your code here, just use the

DOM Ready event listener to kick off your init function

(function ($, undefined) { var app = { init: function() { // Do init stuff here } }

$(app.init); // app.init called on DOM ready // Same as: $(function() { app.init(); }); // or: $(document).ready(function() { app.init(); });}(jQuery));

Page 41: Blind faith and best practices   mike behnke   @localpcguy

CACHE YOUR SELECTORIf you are using a jQuery lookup more than once,

cache the lookup in a variable

$('#item').text('Lorem Ipsum');$('#item').css('color': '#c00');

// vs.

var $item = $('#item');

$item.text('Lorem Ipsum');$item.css('color', '#c00');

Use a $ to designate that it is a jQuery object. Controversial?

Page 42: Blind faith and best practices   mike behnke   @localpcguy

CHAIN WHEN POSSIBLEUse chaining

Format it nicely, more readable, better for debugging also

$item .text('Lorem Ipsum') .css('color', '#c00');

But don't abuse chaining$(this).html("Back") .siblings("ul") .stop() .css({"top":0,"opacity":1.0}) .fadeOut(500) .focus() .find("li:last") .addClass("lastTestimonial") .parent() .parent() .parent() .addClass("viewAll") .animate({width:697+"px"}, 1000) .find(".testimonialsCntnr") .animate({width:697+"px"}, 1000, function(){ $(".seeAllTestimonials") .siblings("ul")

Page 43: Blind faith and best practices   mike behnke   @localpcguy

PREFER .FIND() AND .CLOSEST()More robust and succint than .children() or.parent()/.parents() for traversing the DOM

<div class="wrap"> <ul> <li> <p><span class="elem">stuff</span></p> </li> </ul></div><script> var $elem = $('.wrap').find('.elem'); var $wrap = $('.elam').closest('.wrap');</script>

Page 44: Blind faith and best practices   mike behnke   @localpcguy

PREFER DEFINED FUNCTIONS TO ANONYMOUSWHEN POSSIBLE

Cleaner, easier to read codeLess nesting

(function ($, undefined) { var theater = { init: function() { // Setup control events $('.thtrWrap').on('click', '.theaterNavLink', theater.changeSlide); $('.thtrWrap').on('click', '.theaterLeft', theater.slideNavPrev); $('.thtrWrap').on('click', '.theaterRight', theater.slideNavNext); }, changeSlide: function(e) { // ... }, slideNavPrev: function(e) { // ... }, slideNavNext: function(e) { // ... } } $(theater.init); }(jQuery));Bonus: Event delegation. Tip: listen on the

closest parent element that isn't dynamic

Page 45: Blind faith and best practices   mike behnke   @localpcguy

DON'T PRE-OPTIMIZEjQuery Sizzle (selector engine) is very fast

BUT BE WARY OF .EACH()Loops can be slow with .each(),

consider using a for loop

Page 46: Blind faith and best practices   mike behnke   @localpcguy

TOOLSNot Best Practices

Page 47: Blind faith and best practices   mike behnke   @localpcguy

BUILDGruntGulpMimosaAnt, Make, Jake

Page 48: Blind faith and best practices   mike behnke   @localpcguy

SCAFFOLDINGYeomanLineman

Page 49: Blind faith and best practices   mike behnke   @localpcguy

LANGUAGESfor tools to work

Node.jsRuby

Page 50: Blind faith and best practices   mike behnke   @localpcguy

FRAMEWORKSBackboneAngularEmberBootstrapFoundation

Page 51: Blind faith and best practices   mike behnke   @localpcguy

There is a reason we have so many people touting best practices,new frameworks, even new languages

FOR LOVE OF KITTEN PHOTOS, RIGHT?

Page 52: Blind faith and best practices   mike behnke   @localpcguy

IT'S ABOUT PASSIONWe love this business, we love making things.

We set best practices to ensure the businesswe love presents it's best face forward.

Page 53: Blind faith and best practices   mike behnke   @localpcguy

"BLINDLY FOLLOWING BEST PRACTICESIS NOT A BEST PRACTICE."

- DAVE MARKEL

Page 54: Blind faith and best practices   mike behnke   @localpcguy

ABOUTMIKE BEHNKE

Front End Focused Engineer,dabble on the server-sideJavaScript & Android EnthusiastTech geek, futurist

Site: Tweets: GitHub: Slides: Employed:

(We are hiring)

[email protected]/LocalPCGuy

http://lpg.io/best-practicesEnlighten Agency


Recommended