alexkras.com

  • Home
  • YouTube
  • Tech News TLDR
  • Top Posts
  • Resume
    • Projects
  • Contact
    • About

Archives for June 2014

Summary of Maintainable JavaScript Talk by Nicholas C. Zakas

June 28, 2014 by Alex Kras 16 Comments

Share this:

Why do we care? Most of out time is spent maintaining code.

If you open an editor and:

  • It’s blank – you are writing new code.
  • Something already there – you are maintaining code.

Most of us learned JavaScript on our own and developed our own “best” practices

Maintainability = Developing as a Team

What is Maintainable code

Works for 5 years without having to rewrite


Maintainable code is:

  • Intuitive – You look at it and it kind of makes sense.
  • Understandable – If you look at something more complicated for a while, you can understand what it does.
  • Adoptable – You want other people to be able to come in and make changes without feeling that the code is going to explode.
  • Extendable – You can build on top of the existing code to do more things.
  • Debug-able – Set up your code so somebody can step through it and figure out what it does.
  • Testable – If you can write unit and functional tests, it will save you a lot of time.

Be Kind to Your Future Self!
Chris Eppstein, Creator of Compass

Code Style

Communicate with each other through the code – Programs are meant to be read by humans

Style guides

  • Popular Style Guides
    • Crockford
    • Google JavaScript Style Guide
    • jQuery Core Style Guide
    • idiomatic.js
  • Pick a style for the team and stick to it. (Don’t have everybody indent the code however they like etc.)
  • Minimize amount of code per line – much less likely to have a merge conflict.

1
2
3
//Bad
if(found) { doSomething(); doSomethingElse();}
else { doMore(); doEvenMore();}

  • Best to space things out.

1
2
3
4
5
6
7
8
//Good
if(found) {
    doSomething();
    doSomethingElse();
} else {
    doMore();
    doEvenMore();
}

Comments

  • You shouldn’t have to read through entire file to understand what the code is doing.
  • Not too many comments though, just like good seasoning in cooking – just the right amount.

At the very least:

  • Add JaveDoc style comments at the top of each function.

1
2
3
4
5
6
7
8
/**
* A simple demo function that outputs some text
*
* @param {String} text The text that will be written to console
*/
function demoFunction(text) {
    alert(text);
}

  • For a difficult to understand code.

1
2
3
4
5
6
7
8
9
10
switch(mode) {
    case 1: //First Visit
        doSomething();
        break
    case 2: //Every other visit
        doSomethingElse():
        break;
    default:
        doNothing();
}

  • Code that might seem wrong at a first look

1
2
3
while(element && (element = element[index])) { //Note: testing assignment, do not edit
    doSomething();
}

  • Browser specific code (i.e. IE6 workaround)
  • Make sure to add a comment, otherwise a helpful colleague will fix it for you 🙂

Use logical names for your functions and variables

  • Don’t worry about length, you can compress it during build process.
  • Variable names should be nouns (i.e. var book).
  • Function names should begin with a verb (i.e. getName()).
  • Avoid names that have no meaning (i.e. var a; function foo()).
  • Use camel casing since camelCasingIsTheJavascriptWay.
  • For Constant-like variables use – UPPER_CASE_WITH_UNDERSCORE.

Programming Practices

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.
C.A.R Hoare, Quick-sort Developer

Keep Front Layer Separate

  • CSS – Presentation
  • JavaScript – Behavior
  • HTML – Data/Structure

Rules of the road

  • It is not intuitive to look for html code in javascript file, or for javascript code in html file
  • Keep your JavaScript out of HTML
    • Avoid <button onclick="doSomething()">Click Me</button>
  • Keep your HTML out of JavaScript
    • Avoid element.innerHTML = "<div class=\"popup\"></div>"
  • Keep JavaScript out of CSS
  • Use Templates!!!

Event Handlers should only handle events

  • Bad Example

1
2
3
4
5
6
7
//The wrong way!!!
function handleClick(event){
    var popup = document.getElementById("popup");
    popup.style.left = event.clientX + "px";
    popup.style.top = event.clientY + "px";
    popup.className = "reveal";
}

  • Better Example – factor out function so it can be passed around and tested

1
2
3
4
5
6
7
8
9
10
11
//Better, but still wrong
function handleClick(event){
    showPopup(event);
}
 
function showPopup(event){
    var popup = document.getElementById("popup");
    popup.style.left = event.clientX + "px";
    popup.style.top = event.clientY + "px";
    popup.className = "reveal";
}


  • Even better, don’t pass event object. Extract data that you need and pass that on to the function.

1
2
3
4
5
6
7
8
9
10
11
//Good
function handleClick(event){
    showPopup(event.clientX, event.clientY);
}
 
function showPopup(x, y){
    var popup = document.getElementById("popup");
    popup.style.left = x + "px";
    popup.style.top = y + "px";
    popup.className = "reveal";
}

Do Not modify objects that you do not own

1
2
3
4
5
6
7
8
9
//i.e. We extended
Number.prototype.toFoo = function() { return "bar" };
Number(1).toFoo(); //Returns "bar"
 
//2 months later, developers at Chrome decide to implement the same method as
Number.prototype.toFoo = function() { return "baz" };
 
//It may break your code. And even if you force it to work, you could have a new co-worker join your team
//who would expect Number(1).toFoo() to return "baz" and she will be very confused to see "bar" instead.

  • Modifying existing methods is bad
  • Adding new methods is also bad. You don’t know what will happen in the future, what methods might be added to the original object.

Throw your own errors when you know functions will fail

  • It’s like another note to self or other programmers, when things might be hard to figure out.

1
2
3
4
5
6
7
8
var Controller = {
    addClass: function (element, className){
        if(!element){
            throw new Error("addClass: 1st argument missing");
        }
        element.className += " " + className;
    }
}

Avoid null comparisons, unless null value is specifically assigned

  • Bad

1
2
3
4
5
6
7
8
9
function(items){
    if(items != null){
        items.sort();
    }
    //Will work with:
    //var items = true;
    //var items = 1;
    //var items = "blah";  
}

  • Better communicate your intention and prevent false positive with:

1
2
3
4
5
function(items){
    if(items instanceof Array){
        items.sort();
    }
}

  • Use:
    • instanceof to test for specific object types
      • object instanceof MyType
    • typeof to test for primitive types
      • typeof value == "string"
    • BEWARE typeof null == object

Separate config data

  • Bad – Need to factor out items that might change

1
2
3
4
5
6
function validate(value) {
    if(!value){
        alert("Invalid value");
        location.href = "/errrors/invalid.php";
    }
}

  • Keep items data away from your application logic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var config = {
    urls: {
        invalid: "/errors/invalid.php"
    },
    strs: {
        invalidmsg: "Invalid value"
    }
};
 
function validate(value) {
    if(!value){
        alert(config.strs.invalidmsg);
        location.href = config.urls.invalid;
    }
}

  • When you change data, you shouldn’t have to re-run unit tests to make sure logic is still the same
  • Items to factor out
    • URLs
    • All String displayed to user
    • Any HTML that needs to be created from Javascript – use templates.
    • Settings (i.e. Number of items per page)
    • Unique values that are repeated multiple times

Automation (make everybody’s life easier)

Build process is magic

  • Add/Remove debugging code
  • Concatenate files
  • Generate Documentation
  • Validate Code
  • Test Code
  • Minify Files
  • Deploy Files

Build tools

  • js-build-tools – easy preprocessors. Supports:

1
2
3
// #ifdef debugEnabled
someFunction();
// #endif

Documentation Tools

  • JSDOC
  • YUI docs
  • Docco

Linting

  • JSLint
  • JSHint (More config options)

Compressors

  • Uglify JS
  • Closure Compiler
  • YUI compressor – Deprecated

Task Runners

  • Ant (Note: Ant was probably a good advice back in 2012, but today I would just use Grunt)
    • Good blogpost on how to use Ant for JS and CSS minifcation
  • Grunt

Build types

  • Development
    • Add/Remove Debugging
    • Validate Code
    • Test Code
    • Generate Documentation
  • Testing
    • Add/Remove Debugging
    • Validate Code
    • Test Code
    • Concatenate files
    • Minify Files
  • Deployment
    • Add/Remove Debugging
    • Validate Code
    • Test Code
    • Concatenate files
    • Minify Files
    • Deploy Files

Summary

  • Use style guidelines
  • Loose coupling of layers makes changes and debugging easier
  • Good programming practices allow for easier debugging
  • Code organization and automation help to bring sanity to an otherwise crazy process

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
(Unknown)

More about Nicholas C. Zakas

http://www.nczonline.net/
@slicknet

Please Share:

Wanna see my pretty face and hear me ramble? Check out my YouTube channel 🙂

P.S. Check out Disrupted: My Misadventure in the Start-Up Bubble by Dan Lyons a co-producer and writer for the HBO series Silicon Valley (sponsored).


P.P.S. Let's connect on Twitter, Facebook or LinkedIn. You can also get updates via RSS Feed or the Email Form Bellow.
Follow @akras14

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

You may also like:
Share this:

Filed Under: JavaScript

Batch Rename Files in Unix Command Line

June 27, 2014 by Alex Kras 1 Comment

Share this:

Sometimes the unix shell script is still the best tool for the job.

Today I needed to rename a bunch of java properties files from *.property to *.json. Ok, I needed to do more then just rename them, but it makes the example easier to assume that is all that I needed done 🙂

I wrote the following script in rename.sh file.


1
2
3
4
#!/bin/bash          
for file in *.properties; do
  mv "$file" "${file%properties}json"
done

Then I ran chmod +x rename.sh followed by ./rename.sh to run the file. Done.

It’s a small example, but it demonstrates well just how powerful bash scripts can be.

Please Share:

Wanna see my pretty face and hear me ramble? Check out my YouTube channel 🙂

P.S. Check out Disrupted: My Misadventure in the Start-Up Bubble by Dan Lyons a co-producer and writer for the HBO series Silicon Valley (sponsored).


P.P.S. Let's connect on Twitter, Facebook or LinkedIn. You can also get updates via RSS Feed or the Email Form Bellow.
Follow @akras14

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

You may also like:
Share this:

Filed Under: Uncategorized

Easy Way to Run JavaScript Tests On Multiple Browsers Using Free Tools

June 3, 2014 by Alex Kras Leave a Comment

Share this:

tl;dr

  • I though of an interesting idea that helps me test my JavaScript code simultaneously on multiple browsers using two free tools ngrok and screenshots from BrowserStack.
  • Simply pipe your JavaScript tests running on localhost through ngrok to make them accessible to the real world. Then use that link on BrowserStack to generate screenshots on multiple browsers running on multiple environments.

The problem

I have to manual run my tests across multiple browsers to make sure that they are passing under different environments.

For example, let’s imagine I wrote the following test to make sure that I can use ogg video type across multiple browsers.

1
2
3
4
5
6
7
describe('browser', function() {
    it('should support ogg video', function() {
        var vidTest = document.createElement("video");
        var oggTest = vidTest.canPlayType('video/ogg; codecs="theora, vorbis"');
        assert(oggTest === 'probably', "ogg video is not supported");
    });
});


As you can see from http://caniuse.com/ogv the answer is no. But bear with me for the sake of this example.

To make sure that ogg format is sufficient, I would need to run this test in every browser that I want to support. Obviously, this can get old fast.

The Solution

A while back I wrote about a great tool, called ngrok that lets you pipe your localhost to the real world. You can read more about it here.

You also may have heard of a site called Browserstack that allows you to generate screenshots of your site running on multiple environments.

If you combine the two, you can pipe your tests running on the localhost to ngrok. Then use that link to go to BrowserStack and run your test on whichever environments they support.

Sample Result

In my example above, I pipped my test runner through ngrok, copied the link, went over to BrowserStack and selected IE10, Chrome, and Firefox running on Windows 7.

browserstack-browsers

I got the following results.

browserstack-all

From a quick glance at the results, it is easy to tell that something is wrong with IE. If I click on the test results I’ll see that in fact, IE does not support ogg filetype.


browserstack-detail

I can then fire up Windows 7 with IE10 on a virtual machine, and debug the issue further.

Please Share:

Wanna see my pretty face and hear me ramble? Check out my YouTube channel 🙂

P.S. Check out Disrupted: My Misadventure in the Start-Up Bubble by Dan Lyons a co-producer and writer for the HBO series Silicon Valley (sponsored).


P.P.S. Let's connect on Twitter, Facebook or LinkedIn. You can also get updates via RSS Feed or the Email Form Bellow.
Follow @akras14

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

You may also like:
Share this:

Filed Under: JavaScript

Copyright © 2018 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in