Blind Faith andBest Practices – Enter...The Best Practice – HTML



Blind Faith andBest Practices – Enter...The Best Practice – HTML

0 0


selfconf-blindfaithandbestpractice

Blind Faith and Best Practice slides from SelfConf

On Github localpcguy / selfconf-blindfaithandbestpractice

Blind Faith andBest Practices

Mike Behnke@localpcguy

Let's dive into best practices and find more about what they are and why we care

I'm Mike Behnke, and I want to chat about a programmer's journey as they start out

Starting Out

As programmers, we all start somewhere. I started with Basic, on a Commodore Plus 4, a failed relative of the popular Commodore 64. Anyone know about those?

Front end dev for Enlighten Agency

Programmer's Journey

As programmers start out, like an old map - remember when you looked at these?

Things are the wrong size, shape. Some areas are just "unknown, here there be dragons"...

Kinda like new programmers when they get started

They have a general idea of what they are doing, but things in this area are fuzzy, over there is stuff that is completely foreign/unknown..."here there be closures"

As you program, run into problems, hacky solutions

As you progress, you start to know that your hacks are bad, so start looking into what you "should" do instead

Start looking around and say, "there must be a better way"

There must be a better way

At some point while learning, we've all come to this point, right?

Enter...The Best Practice

Commercial or professional procedures that are accepted or prescribed as being correct or most effective.

Best Coding Practices

==a set of informal rules that the software development community has learned over time which can help improve the quality of software.

in our industry, being rather young still, more informal

Still, there are a variety of Best Practices

Are B.P. misguided attempts to control devs

Misguided?

  • Most "Best Practices" in Software Engineering are there to keep bad programmers from doing too much damage
  • The only "best practice" you should be using all the time is "Use Your Brain"

Many people feel that best practices are just misguided attempts to force everyone to do things the same way

no allowance for innovation or immagination

Blind Faith?

==a belief without true understanding,perception, or discrimination

Are Best Practices just blind faith inpeople that came before usor that we deem smarter than us?

  • Brings us to Blind Faith part from the name of the talk. What is it?
  • Are Best Practices just another term for Blind Faith?
  • Or do we take the time to educate and decide for ourselves?
  • It's easy to see someone giving a talk, or representing a large company, and take their word for it that this is the way things should be done.

My Goal

To encourage everyone to look at best practices and know WHY they use the ones they do, and WHEN to discard ones that no longer are effective.

And To Encourage Best Practices...But

Make sure they really are, and know when to follow them

And when to ignore them

Examination

Let's take a look at some best practices

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

photo by Sara Cimino

HTML

Semantics Matter

Help screen readers, Google, and othermachines/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>

HTML5 Semantics

Lets talk about semantics

Everything in the proper place

  • JavaScript:   - 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

HTML5 Boilerplate

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

great to read through some of the issues, lots of reasoning for why things are done different ways, or to look back through the history of the code for how it's evolved over time

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>
        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>

        <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
        <script>
            (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
            function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
            e=o.createElement(i);r=o.getElementsByTagName(i)[0];
            e.src='//www.google-analytics.com/analytics.js';
            r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
            ga('create','UA-XXXXX-X');ga('send','pageview');
        </script>
    </body>
</html>

CSS

General Rules

  • Use a reset (or normalize) style sheet
  • Avoid 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]-->

Clean Stylesheets

Provide Stylesheet information and indicate structure

/* stylesheet for Corp Bar
File created date: 09.15.2010
Last modified date: 06.04.2012
By: [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.)

Selectors

  • Avoid IDs for styling - specificity problems, not reusable
  • As short as possible, reduce specificity
  • Use 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;
}

Multiple files

Prefer multiple, smaller CSS files over a single monolithic file.

Concatenate and minify for performance

PreProcessors

Quickly becoming best practice to use a preprocessor

  • Adds to developer efficiency
  • Reduces errors
  • Prevents repetition
  • Careful: Don't over-complicate things
  • Careful: Don't over-nest selectors

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

See Getting Sassy with CSS from yesterday's talks by Julie Cameron

Which one is not ever a "best practice"

Modularize your CSS

SMACSS is a popular style

  • Make elements portable, reusable
  • No 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>

Frameworks

Bootstrap and Foundation are very popular now

They are NOT best practices by themselves however

But they do enable best practices in many cases

And allow developers to gain efficiency

JavaScript

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 problems
if(1 === '1') //Returns false
if(1 == '1') //Returns true

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

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

Saw Kyle Simpson tout this at HTML5 Dev Conf, and if you know the difference and use them appropriately, all good.

Caveat - Keep in mind other members of your team and if it'll be a stumbling block for them.

Use your Semicolons!

var a = obj
[a].forEach(logProp)   // 'fail' : var a = obj[a].forEach(logProp)

Source - Ben Alman

Always use curly braces

Goto 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

Blocks

Opening curly brace for blocks should go on thesame line as the declaration (in JavaScript)

function foo() {
    var bar = 1;

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

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?)

important thing is not whether it's 2 or 4, but that everyone is aligned the same way

no need to be dogmatic with others, it's mostly personal preference

JSLint (or Hint) Your Code

Catch errors before you refresh.

SublimeLinter

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 variables
  • Prevents duplicate properties
  • Prevents accidental function overwrite
  • Makes eval (a bit) less evil

Encapsulate your Code

(function(){ 
    // Do stuff here
}());

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

Use the Module Pattern

var 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 JavaScript module patterns and variety of examples and links to more reading

jQuery

Still use jQuery?

  • Makes the DOM tolerable
  • On a diet lately (only 32KB minified/gzipped)
  • Cross-browser compatibility, events, ajax
  • Plugins
  • Trusted by >50% of websites online

jQuery IS JavaScript

So LEARN JavaScript first (at least the basics)

lpg.io/web-dev/javascript-resources

Isolate jQuery

Pass jQuery into your module

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

Bonus: undefined really is undefined

jQuery Ready

Don't put all your code here, just use theDOM 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));

Cache your selector

If 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?

Some people object to the $ saying it is just Hungarian notation, the idea of putting the type before the variable, i.e. iItem for int or strItem for string. Personally, I think it is just a super identifier, that doesn't need to be compared to full Hungarian notation.

Chain when possible

Use 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")
            .addClass("isFullyOpen")
            .fadeIn(500);
            testimonialsBelt.resetBelt();
            isAnimating = false;
         });

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>

.filter() vs. .find() ?

Prefer defined functions to anonymous when possible

  • Cleaner, easier to read code
  • Less 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 theclosest parent element that isn't dynamic

Don't pre-optimize

jQuery Sizzle (selector engine) is very fast

But be wary of .each()

Loops can be slow with .each(),consider using a for loop

Tools

Not Best Practices

Build

  • Grunt
  • Gulp
  • Mimosa
  • Ant, Make, Jake

Scaffolding

  • Yeoman
  • Lineman

Languages

for tools to work

  • Node.js
  • Ruby

Frameworks

  • Backbone
  • Angular
  • Ember
  • Bootstrap
  • Foundation

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

For love of Kitten photos, right?

It's about Passion

We love this business, we love making things.We set best practices to ensure the businesswe love presents it's best face forward.

"Blindly following Best Practicesis not a Best Practice."

- Dave Markel

Don't be dogmatic, know why you do what you do.

About

Mike Behnke

  • Front End Focused Engineer,dabble on the server-side
  • JavaScript & Android Enthusiast
  • Tech geek, futurist