Silicon Valley Code Camp 2011

Last weekend myself and Omid Mozayani (another Aussie; recent addition to the valley) spent the weekend of Saturday and Sunday, October 8th and 9th, 2011 at Silicon Valley Code Camp 2011. Held at the Foothill College in Los Altos/CA with an attendance of well over 2,000 (registered 3,417) people and 209 sessions organized in a University style setup over these 2 days. Impossible to attend each one but plenty to cherry pick from. It felt like I was back at Uni(versity) running between lectures. I loved it! Here’s what happened.

What is Code Camp

Code Camp is a new type of free community event by and for the developer community where developers learn from fellow developers. It is 2 full days of talking about code with fellow developers. Sessions range from informal “chalk talks” to presentations. Basically there is lots of education, networking and good food.

Pictures from Code Camp @ Foothill College

Lecture – Crockford on ECMAScript5

Lunch – feeding time for thousands of nerds

Ernest Semerda – nerd out and about

Lecture – multi threaded design

More pictures here on my Flickr.

Code Sessions

Choosing what sessions to attend was key since it was impossible to attend everything when you consider that each session took around 45 min. Here is a wrap of the 3 areas I focused on; ECMAScript (JavaScript) with code encapsulation, Writing Clean Code and Web Analytics. This website will highlight key points.

ECMAScript 5 (JavaScript)

Douglas Crockford ran 2 sessions on ECMAScript 5: The New Parts and ECMAScript: What Next?. Crockford is involved in the development of the JavaScript language and popularizing the data format JSON (JavaScript Object Notation), and for developing JSLint. You may recall me talking about JSLint in a previous blog post on JavaScript Patterns.

More on Crockford is here (his personal site) and here: Crockford on JavaScript. Also read about how JavaScript is the world’s most misunderstood language. Recommended reading! You will want to learn more about this great language.

ECMAScript’s Fifth Edition is now available in all of the best browsers. This is what you are getting:

  • Use “Strict mode” in all your JavaScript code.
    • As per my previous post on JavaScript Patterns here.
    • Old JS compiler ignores it so it’s safe to use today in all your JavaScript.
    • A bug in JS used to advantage today for backward compatibility.
    • “Strict mode” will break old bad programs. If you are writing good programs they will just work.
  • No more implied global variables within functions.
    • Yipee! Major fail in JavaScript where undefined variables would chain to the prototype making it very difficult to isolate your code, and to reuse it in new contexts.
    • If you forget to “var” a variable it now becomes undefined so you can address it vs. letting it slide by. Bad coders beware!
    • To append something to the global object add “window.function/var”.
  • “apply” and “call” do not default to the global object.
  • No “with” statement. Read why it was considered harmful to use.
  • Restrictions on “evil” eval. Here’s why it’s evil. *Cough* code injection!
  • No more octal literals. Not needed since punch card days.
  • Forgetting to use the new prefix will now throw an exception, not silently clobber the global object.

Use something like this today to check if your browser is running in Strict mode:

function in_strict_mode() {
    return (function () {
        return !this;
    }
}
  • Make it a habit to do static analysis using JSLint. If you are using it already your code is probably good and ready for strict mode.
  • Use “Safe JavaScript Subsets” like Caja & ADsafe projects which allow you to safely run 3rd party software on your website.

JavaScript Code Organization and Encapsulation

Shawn Van Ittersum presented ideas for organizing, encapsulating, and simplifying JavaScript code, including: creating JavaScript objects and classes with truly private members, using Douglas Crockford’s module pattern and classical inheritance constructs provided by Dean Edward’s Base.js, Prototype, and MooTools; abstracting JavaScript code from HTML templates, CSS styling, and the DOM; designing with polymorphism (duck typing) for code reuse and simplicity; and using JSLint to identify problems in your code before runtime.

The idea behind the power of Encapsulation is simple:

  • Encapsulation limits widespread interconnection,
  • Gives you Freedom to change internal implementations without affecting external code and
  • is referred to as Loose Coupling – an approach viewed as positive in the field of computer science to remove dependency between systems and allow horizontal scaling.

Ittersum’s lides with code samples are located here.

Writing Clean Code

Theo Jungeblut ran this session and basically the crust of the presentation was that writing clean code makes us more efficient.

This presentation was based on C# and Visual Studio 2010. However the following patterns and practices can be applied to every other programming language too.

Over the lifetime of a product, maintaining the product is actually one – if not the most – expensive area(s) of the overall product costs. Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code.

  • Readability
    • Follow coding guidelines.
  • Simplification and Specialization
    • KISS (Keep it simple, Stupid!) – most systems work best if they are kept simple rather than made complex.
    • SoC (Separation of concern) – focus on 1 thing.
    • SRP (Single responsibility principle) – every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.
    • OCP (Open/closed principle) – software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification aka inheritance & encapsulation.
  • Decoupling
    • LSP (Liskov substitution principle) – guarantee semantic interoperability of types in a hierarchy, object types in particular.
    • DIP (Dependency inversion principle) – high-level modules should not depend on low-level modules. Both should depend on abstractions. And abstractions should not depend upon details. Details should depend upon abstractions.
    • IHP (Information hiding principle) – prevent certain aspects of a class or software component from being accessible to its clients aka encapsulation.
    • Contracts – 2 categories: preconditions and postconditions where a precondition states that certain things must be true before a method can execute, and a postcondition states that certain things must be true after a method has executed.
    • LoD (Law of Demeter or Principle of Least Knowledge) – specific case of loose coupling where units (code) only talk to immediate friends (not strangers) assuming as little as possible about the structure or properties of anything else.
    • IoC (Inversion of control) – reusable generic code controls the execution of problem-specific code. It carries the strong connotation that the reusable code and the problem-specific code are developed independently, which often results in a single integrated application.
    • SOA (Service-oriented architecture) – develop code in business functionalities (discrete pieces of code and/or data structures) that can be reused for different purposes.
  • Avoiding Code Blow
    • DRY (Don’t repeat yourself) – reduce repetition of information.
    • YAGNI (You ain’t gonna need it) – do not add functionality until it is necessary.
    • Quality through testability (all of them!)

There is also a good bunch of tips from The Pragmatic Programmer located here.

And don't forget, Scout rule = leave a better place!

Recommended book

SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) is a mnemonic acronym introduced by Robert C. Martin

Web Analytics

Massimo Paolini presented on Google Analytics. The most profound thing he said which delivered a strong message is:

"Web analytics is about Revenue NOT traffic."

Bang! Right there. Too many site owners are mislead into trying to decipher visitor totals vs. focusing on the true picture; and that is how to understand and optimize their site visitors across online marketing efforts. The process is then rinse & repeat.

Finally, Web Analytics is NOT a precise science. You are looking for trends. Differences. To help you make decisions moving forward. This is because some people clean their systems ie.delete cookies etc..

Presentations from Silicon Valley Code Camp

For more presentations from these 2 days follow the link below to presenter uploaded presentations to SlideShare. Includes 2011 and previous years. Enjoy!

http://www.slideshare.net/search/slideshow?type=presentations&q=silicon+valley+code+camp+2011&searchfrom=basic

More links to Silicon Valley Code Camp

Code Camp main site: http://www.siliconvalley-codecamp.com/
On Facebook: http://www.facebook.com/groups/6125701762/
On PB Wiki: https://codecamp.pbworks.com/w/page/16049741/FrontPage
On Twitter: http://twitter.com/#!/sv_code_camp

So, in conclusion, this was an awesome & insightful 2 days packed with plenty of great applicable content.

Enjoy!
~ Ernest

ECMAScript: The history of JavaScript

JavaScript is a very interesting language that has caught my eye in the last year. Previously I blogged about the power of the Module Pattern in JavaScript; why it’s powerful and how to make sure your site complies to this great pattern. The language has come a long way and is growing up fast to be the defacto language of choice for all front-end UI/behavioral functionality. Flash, the old heavy dog, is on its way out. JavaScript, part of the HTML5 stack, is looking the most promising.

This post isn’t about how great JavaScript is, it’s about its history. Before one delves into anything one should always understand the basics. So let’s begin with some basics and then its history. The history is rather interesting.

What is JavaScript anyway?

JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions.

For the business guy

  • JavaScript is client-side language. Meaning anyone with a browser can view it in its entirely. Nothing is hidden. This is how we have access to any site’s code. Right click on any webpage and select “View Source” – Bingo!
  • JavaScript is downloaded via your browser and then executed within the browser. This is where performance bottlenecks are experience and browser compatibility issues.
  • JavaScript’s real name is actually ECMAScript.

For the tech guy

  • JavaScript is a “prototype-based scripting language” meaning it is object-oriented where classes are not present, and inheritance is performed via a process of cloning existing objects that serve as prototypes.
  • JavaScript is “dynamic”; meaning that it executes at runtime.
  • JavaScript is “weakly typed”; meaning you can cast memory to any type and
  • JavaScript has “first-class functions”t meaning it supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

History of JavaScript

There are many stories online but I think this one below (source) explains it nicely.

Here is something else you should know about Javascript that seems like it was almost designed to be confusing as possible:

  • There is a programming language called Javascript.
  • There is a programming language called Java.
  • There is an interpreter (‘thing that makes it go’) for the programming language Javascript built into most web browsers
  • There is an interpreter for the programming language Java that is sort of built in to most web browsers, or was.
  • THESE TWO PROGRAMMING LANGUAGES HAVE ALMOST NOTHING TO DO WITH EACH OTHER

Back in the olden days, there was a company called Sun that had invented a programming language they decided to call Java. It was very trendy and exciting. There was a company called Netscape that made the trendiest and excitingest web browser. Sun wanted Netscape to include the magical crap that would make Java work with their browser, because everyone was gonna get Netscape, so everyone would also automatically have the stuff that makes Java programs work. On the other hand, Netscape was saying, “but lets also make our own tiny programming language that runs right in the browser so instead of having to make up new html tags like ‘blink’, web authors can make annoying shit we haven’t even thought of yet!” So they said, “Sun, we’ll ship your ‘Java’, but we want to be allowed to call our other programming language, which has absolutely no relationship to yours and is intended to do completely different things, JavaSCRIPT.” And Sun said, “OK, swell. go nuts. That won’t matter to us. ONCE JAVA TAKES OVER THE WORLD!”

So Netscape said to a guy named Brendan, who worked at Netscape, “Please make us a programming language. Also, you have to call it Javascript. Also, if you can make some of it kind-of sort-of look a bit like Java, that would be even better. Also, you have only 10 days to do this so get cracking!”

Fortunately, it turned out that Brendan was a cool genius and he secretly designed a cool programming language and dressed it up in some vaguely Java-looking disguises, kind of like how children will sometimes wear a huge cloak and stand on top of one another in order to get into R-rated films.

But Brendan’s disguise worked too well! People were like “wtf is with this crap version of Java? IT SUCKS!” Also, even a cool genius like Brendan has some some limits, so he did make a few mistakes when he was making his programming language in only 10 days. Also, because Netscape had basically thrown down the gauntlet and said, “You think the blink tag is annoying? Marquee makes you want to rip your eyeballs out? YOU HAVEN’T SEEN NOTHING!” people did manage to find insanely annoying things to do with Javascript. All the cool people installed special software on their web browser JUST TO MAKE JAVASCRIPT NOT WORK. So it took many years before people started to figure out that Brendan’s language was wrapped in an elaborate disguise and that it was actually cool.

Weirdly, some of the main people who did this were people at Microsoft, who had tried to confuse this whole mess out of existence by coming out with programming languages named stuff like J++ and JScript. Netscape, at the time, was threatening to rip Microsoft apart, like a crab rips up a cuttlefish with his claws. So Microsoft, adopting the strategy of the cuttlefish, made a million confusing “J” programming languages, hoping to escape intact. A prophet by the name of Douglas started saying, “guess what nerds, it turns out Javascript is actually sort of awesome.” He managed to attract a fair number of acolytes, who fiddled with Brendan’s invention and realized that it was rather elegant and could certainly be made to do all sorts of useful, non-annoying things on webpages, if only people would stop blocking it.

And so the era now known as Web 2.0 began. There are a lot of things people associate with Web 2.0, but for people who make the internet, one of the biggest things was seeing sites like Flickr or Oddpost do cool stuff with Javascript and other technologies that had been previously considered lame.

And then, in a sort of poetic irony that makes this story almost seem like it was pre-scripted to Teach us a Lesson, JAVASCRIPT succeeded in doing what JAVA had intended to do. Microsoft, Java, Sun, Netscape, all were brought low by their hubris. But humble Javascript, the throwaway, ‘you get 10 days to make this’, blink-tag-replacing runt of a language was able to sneak onto every computer in the world thanks to its clever disguise. Servers are written in Javascript. Databases are built to talk Javascript. The people who build browsers and operating systems move heaven and earth to make Javascript just a tiny bit faster. Java’s still out there, of course. In various forms. It probably makes sure your account is updated when you pay your water bill. It’s making the underpinnings of your android phone work. It’s figured out a way to play host to a zillion new trendier programming languages. But Javascript won the original prize.

Anyway, I’m just pointing this out because I remember the time when I didn’t know the difference between Java and Javascript and I’d find a tutorial for one or an article about the other and I was like “wtf, how do these go together.” The answer is, “they don’t. Marketing people just tried to name them as confusingly as possible.”

JavaScript today is..

  • Used in every website you visit online.. like 99.9999% of them.
  • At the core of famous server-side Node.js, an evented I/O framework.
  • If you heard of beautiful frameworks like jQuery, YUI, and more recently SproutCore and Cappuccino (Objective-J).. all JavaScript.
  • HTML5? replacement for Flash and other slick interface functionality, yap you guessed it.. JavaScript.
  • It is the most important language today!

What next

Plenty more informative & juicy articles on this front are being lined up. Not to mention I am starting a fun project with few smart software engineers in the valley which aims to give back to the community around this most important language today, JavaScript. Stay tuned to find out more on what’s next!

~ Ernest

JavaScript: made better using the Module Pattern

I’ve just finished reading JavaScript Patterns by Stoyan Stefanov and boy has it opened up my mind and inspired me to write better, faster, cleaner and more modular JavaScript code using the Module Pattern.

Stoyan’s book covers many patterns and anti-patterns (the common old approach to JavaScript coding).

Stoyan provides detailed explanations why and where to use each pattern inc. module pattern. Since there is so much content in this book I decided to write about what I believe will add immediate value to any developer working with JavaScript, how to make JavaScript better using the module pattern.

No hacks around poor JavaScript

JavaScript is unlike back-end server-side code where if the code becomes a bottleneck you just throw more boxes (hardware) at it to speed thinks up. JavaScript downloads & runs within the user’s browser. So if you got lazy or just didn’t know better to follow Convention over Configuration (CoC) or the rapid development principle of Don’t Repeat Yourself (DRY) and you hacked something together.. the user will get poor experience and even limited to a single browser. This is where JavaScript Patterns play an important role and understanding them is the 1st step in becoming a JS Ninja.

JavaScript – what you need to know

Let’s shake some old grounds and cover the what you need to know about JavaScript in 2011.

  • There are no classes in JavaScript. You create a blank object when you need one and then start adding members to it.
  • Sometimes when people say “Singleton” in a JavaScript context, they mean the Module Pattern – covered below and discussed in detail in Stefanov’s Chapter 5. Every time you create an object using the object literal, you’re actually creating a Singleton. And there’s no special syntax involved.
  • When you think about objects in JavaScript, simply think about hash tables of key – value pairs. Similar to what are called associative arrays in other languages.
  • Use literal notation patterns instead of object definitions. Literal is more concise, expressive and less error-prone. See Appendix 1.1 at the end of this post for examples.

Module Pattern – organize your code

Let’s start with what’s most common out there on the internet. You may have seen (or even do) this.

Code sample – anti pattern

Declaring:

var array_string = "[object Array]";
var ops = Object.prototype.toString;
var MAX_NUM = 123;

function inArray (haystack, needle) {
    for (var i = 0, max = haystack.length; i < max; i += 1) {
        if (haystack[i] === needle)
            return i;
    }
    isEnabled = false;
    return −1;
}

function isArray (a) {
    return ops.call(a) === array_string;
};

var pageTitle = "New title";

Calling:

isArray(arr_user);

The problems here are:

  • All these are global (variable and functions) are shared among all the code in your application living in the global namespace. High chance of naming collisions between your and other developer’s code (think maintenance).
  • isEnabled above has no var declaration so automatically becomes chained to the global namespace outside the function.
  • When something in your code is chained to the top of the prototype it takes longer time to be found then if it’s within a module. I will discuss the JavaScript Prototype in another post and show examples with performance differences.
  • Some best practices are broken – see below what these best practices should be.

Module Pattern – the solution, organize your code

There are many great patterns described in JavaScript Patterns by Stoyan Stefanov but my preference today is to use the Module Pattern. The Module Pattern is widely used because it provides structure and helps organize your code into self-contained de-coupled pieces of code. If you look at the source of jQuery you will find a similar pattern being used.

The Module Pattern is a combination of several patterns described in Stoyan’s book.
They include:

  • Namespaces (Stefanov’s pg.87)
  • Immediate functions (Stefanov’s pg.73)
  • Private and privileged members (Stefanov’s pg.92) and
  • Declaring dependencies (Stefanov’s pg.90)

And here’s how the same sample of code above would look when the Module Pattern was followed.

Module Pattern code sample – the pattern

Declaring:

var MYCOMPANY = MYCOMPANY || {};

// note the use of namespacing - similar to jQuery.
MYCOMPANY.Page = (function () {
    'use strict';

    // [ private properties ]
    // note the chaining of var declarations vs a var on each line
    var pageTitle    = "blank",
        isEnabled    = false,
        array_string = "[object Array]",
        ops          = Object.prototype.toString,
        MAX_NUM      = 123; // constants always are in capital case
    // end var

    // [ private methods ]
    // note the use of literal patterns vs constructor functions
    function inArray(haystack, needle) {
        var i   = 0,
            max = 0;
        for (max = haystack.length; i < max; i += 1) {
            if (haystack[i] === needle) {
                return i;
            }
        }
        return -1;
    }
    function isArray(a) {
        return ops.call(a) === array_string; // end var
    }

    // [ public methods ]
    return {
        init: function (title, enabled) {
            pageTitle = title;
            isEnabled = enabled;
        },
        isArray: isArray,
        indexOf: inArray
    };
}());

Calling:

MYCOMPANY.Page.init('Page title', true);
MYCOMPANY.Page.isArray(arr_user);

Code is now modularized and less prone to collisions.

JSLint: The JavaScript Code Quality Tool

Once you have written your new modularized code it’s a best practice to run it past JSLint. JSLint is a free JavaScript program that looks for problems & violations of some of the patterns in your JavaScript code. It is a code quality tool. Check it out here: http://www.jslint.com/

JavaScript best practices

  • Curly brackets should always be used even if there is 1 expression. Code is then more readable and maintainable.
  • Use 4 space indentation – also JSLint default. This way no matter what editor engineers use it is always displayed in the same manner.
  • Like curly brackets, always use semicolons, even when they are implied by the JavaScript parser. Why slow down the compiler to clean up the mess during runtime.
  • Naming convention for constructors is typically UpperCamelCase, functions lowerCamelCase, variables lowercase_separated_by_underscore and constants UPPER_CASE.
  • Use whitespace as much as possible by separating all operators and their operands with spaces.
  • Use Google’s Closure Compiler to minify your code before production AFTER you have passed it via JSLint (above).

Appendix

1.1 Constructors and their corresponding and preferred literal patterns.

Built-in constructors (avoid) Literals and primitives (prefer)
var o = new Object(); var o = {};
var a = new Array(); var a = [];
var re = new RegExp( “[a-z]”,”g”); var re = /[a-z]/g;
var s = new String(); var s = “”;
var n = new Number(); var n = 0;
var b = new Boolean(); var b = false;
throw new Error(“uh-oh”); throw { name: “Error”, message: “uh-oh” };… or throw Error(“uh-oh”);

And that is it for now. Have I missed something or gotten something wrong above? If so please let me know and I will correct it. How is your JavaScript looking? Need help to get it fixed? Post below or contact me.

~ Ernest