Font Dos & Don’ts

Not a bad reference for some font guidelines:

 

Font dos & Don'ts


Life without a BS Foundation

On April 29th 2014, I presented on a topic titled “Bootstrap and Foundation are not your crutch”. The topic was described as:
 “Although frameworks like Twitter BootStrap and Zurb Foundation are great starting points, examples of good practices, and foundations from which you can easily create prototypes, heavy reliance on these frameworks can create pitfalls that will be felt as the project expands. CSS bloat, lack of knowledge for the underlying framework code, and compromising best practices are examples of mistakes that can happen due to the overuse of these frameworks. The object of this presentation is not only to point out the pitfalls of using these frameworks, but also to provide guidelines on how to take advantage of them.”
And the video of the above presentation is:

(I recommend watching it as I will be referencing some portions of it in this blog post)

However, after some post-presentation hallway chats with some attendees, I have become aware that my message was not well received. The message that the best solution to using CSS frameworks is to NOT use them, was a very hard pill for some to swallow. Although I haven’t changed my opinion on this subject, too many experiences with bloated CSS prevent me to do so, I do empathize with the plight of some. I was given a few scenarios that I will go through one by one and see if we can some to a happy medium conclusion.
TL;DR
Do not panic. You don’t have to go and erase all your CSS code and start from scratch. Like all technical decisions, there are some give and take. It is up to you and your team to evaluate whether the risks that come with implementing a CSS framework is acceptable.  However, what I would recommend, regardless of which option you choose is to follow these guideline:
Before we go through the scenarios, let’s put some goals for us to achieve and also give each goal rating for a final score:
  • Be able to implement the design, layout, and pages to achieve the final product, prototype, etc… (rating: 5)
  • Create the necessary styles and be able to find them easily and maintain them in a timely manner (rating: 3)
  • Avoid CSS bloat and be able to create a performant and extensible CSS base (rating: 2)
I don’t think these goals are radical and I think they should be on the forefront of every project. That being said, let’s look at the scenarios.

“I don’t have the CSS expertise to write my own framework”

Let’s set aside the fallacy that writing a CSS framework requires CSS expertise (before any of these framework were available, we were all writing our own “framework”) and talk about the CSS level needed to complete a project (not build a framework). I will repeat the wisdom of Scott Kellum “CSS isn’t voodoo, it’s a simple and straightforward language where you declare an element has a style and it happens.” The level of CSS knowledge needed to begin is not much. The other questions that must be asked is:

  • Is the framework needed as a starting point?
  • Do you bring the entire framework into the project or do you just bring the necessary modules?
  • What is knowledge level on pre-processors like Sass CSS or LESS?
  • Will you be modifying the pre-compiled code or the final compiled CSS?
  • How much will you be relying on the framework? Do you want to be able to upgrade if new versions becomes available?

So you have downloaded the desired framework and you have started using it. Everything is running smoothly and project is coming along quite nicely. At this point, you have probably built a custom CSS that sits on top of the framework, possibly riddled with “!important” flags (by the way, every time an “!important” flag is used, a CSS fairy loses their wings), and the project is being built according to plan. Then issues arise that may require you to move farther up the CSS chain and actually look into the framework code. This is where the reasoning behind using the framework, the CSS expertise level, will be the reason that will probably bite you in the ass. Where a small issue should’ve been fixed quickly, it has turned into an effort that will take longer than needed.

Goals achieved:
  • We were able to implement the design and build the final product – score 5
  • Not easily find and maintain the code – score 1.5
  • Not much effort in avoiding bloat – score 0
Score:

6.5

“I am just building a prototype”

If you are just building a prototype and you will be using the CSS framework, Bootstrap or Foundation or Inuit, without any customization; then you are in rather good shape. This is one scenario a CSS framework will become very useful, to get ideas in front of consumers and to get feedback. However, this is where the utopian marriage between a CSS framework and a deliverable product ends.

Let us theorize that the happy path of the prototype was built brilliantly (no customization was needed on the CSS) and ideas were communicated and money/investment/green light was bestowed upon all involved. Now the next step of the project is to roll your sleeves up and go beyond the prototype and build the product, which will have a customized design and will involve writing the necessary styles and CSS for the product. What will be the approach? Keep the CSS framework and build on top of it? Or build your own CSS framework? Will you follow the “I don’t have the CSS expertise to write my own framework” approach or will you power through the process and build it? if the code is built on top of the framework, this is where the frameworks will falter. The extension is where it will create some CSS bloat and undesirable results.

Goals achieved:

     Prototype implementation:

  • Able to implement the design, out of the box design – score 5
  • Code maintenance is part of the framework maintenance – score 2
  • No bloat – score 2

Future implementation:

  • Implementation of the design on top of the framework – score 4
  • Code maintenance questionable – score 1.5
  • Extra bloat – score 1
Score:

Prototype implementation:
9

Future implementation:
6.5

“I have already invested a lot of time in <insert CSS framework here> integration”

OK, so you are already chained and committed heavily to your chosen framework. Here are some of the issues that you may confront:

  • Semantic HTML & CSS – frameworks do not write very semantic classes and most names are general purpose names
  • Performance implications – is there any CSS bloat?
  • OOCSS implementation – Is there any Object Oriented CSS implementation?
  • File organization – What is your file organization?
  • Coding convention – Is there a set coding or naming convention?

If you have hit any of these issues, it is a business decision whether to stay committed to the chosen framework or not. The problem is that if the above issues have not reared their ugly heads, they slowly will creep up and eventually will surface either one at a time or all at once.

Goals achieved:

I am not sure as this is a decision that is up to the developer on how much tolerance they have. But since I am grading, here it is:

  • Able to implement the design – score 5
  • Code maintenance – score 0
  • Bloated CSS, yes – score 0
Score:

5

What does all these scores mean?

  • 8=< score =< 10:  You are in good shape and should be high fiving all your teammates
  • 6.5 =< score < 8: There may be danger around the corner like maintenance issues, file organization, or CSS bloat, tread carefully
  • score < 6: Time to evaluate your code and come up with a solution

 

Conclusion

CSS frameworks are filling a void that was among CSS development, there needed to be structure and organization to the CSS code. Frameworks created that, however they cannot be all things to everybody and by trying to be that, is where they fail. If the need is to use a framework, I would highly recommend:

  • Use it bit by bit. Select the modules that you need and don’t bring in the entire framework. Grid system is one I always use.
  • Learn from it.. View the CSS code and learn from it.
  • Use a pre-processor –> Sass CSS (because among all pre-processors, there is no substitute)

Last but not least, these popular frameworks are very opinionated. I don’t think that is a flaw but why not insert your own opinion? Why not establish your own mini framework? One that you are familiar with and know which portions to use as you are going from one project to another. Just an idea.


What would you do with a blank canvas?

An artist starts with a blank canvas, a writer stares at one endlessly. As a developer, there are rare occasions when we are given a blank canvas, a beginning where no decisions have been made, no frameworks have been set and there are endless opportunities and decisions. For some, this may seem like a daunting experience, for me it is an utopian situation.

Most of the times when I start a project, the framework has been previously set and my job has been to inject some best practices where opportunity allows. On personal projects, I do get the opportunity to build from scratch, usually it is to satisfy my curiosity in a certain technology so I haven’t had the liberty (or the forethought) to include all the tools.

However, in recent projects where I have been able to include all the tools available to me and as a result have done most of my projects as such.

So what would you do with such a blank canvas? What tools and frameworks would you use? As a front end developer, this is my list (this list is an approach that considers enterprise development):

NodeJS (as a Web server)

Why use NodeJS and not Apache Tomcat? If you are not familiar with NodeJS, this is a quick description (from their home page):

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Back to question of “Why NodeJS?”. The answer is why not. As a developer whose choice of language is JavaScript, this is ideal where as a developer I can modify the web server and can manage the session, cache, memory, etc… This is on top the evented server side JavaScript which is very light weight and has a good handling on lots of I/O by making the majority of I/O calls asynchronous.

Reference:

NodeJS (as a package manager)

If you chose not to use NodeJS as a web server, it is still a great tool to install on your machine. Installing NodeJS will give you access to Node Packaged Modules (npm) which opens the door to a wealth of packaged modules that can easily be installed on a local machine, enabling the developer to start developing quickly. The other advantage of npm is also that it will allow developers to package up their modules easily to be shared with other developer. As you will see, most of the tools that I am using can be installed through npm.

Reference:

GruntJS

GruntJS is a tack runner which will allow for automation on tasks that as developer we run (or should be running) repeatedly. Tasks like minification, compilation, unit testing, and linting are examples of tasks that can be run every time the developer makes a change. GruntJS is very easy to install and has a large community of developers creating plugins for it.

Reference:

Jasmine

I have been a huge fan of Test Driven Development or Behavior Driven Development. This style of development has several advantages:

  1. Capturing the requirements in human readable form
  2. Unit test is built from the beginning
  3. Test output can be treated as a report
  4. Failures are captured early and often

In order to develop in this approach, Jasmine has been one of the tools that I have used. There are other tools like QUnit and Cucumber (I am exploring Cucumber further and may blog about my experience in the near future). Nevertheless, this approach allows me to think of every requirement in the following manner:

Given a context

When an event happens

Then an outcome should occur

 Reference:

Asynchronous Module Definition (AMD)

Asynchronous Module Definition allows for an approach where the developer thinks of their code as a modular functional area which can be used repeatedly in different areas if needed. Addy Osmani describes this best:

The AMD module format itself is a proposal for defining modules where both the module and dependencies can be asynchronously loaded. It has a number of distinct advantages including being both asynchronous and highly flexible by nature which removes the tight coupling one might commonly find between code and module identity. Many developers enjoy using it and one could consider it a reliable stepping stone towards the module system proposed for ES Harmony.

This approach coupled with a powerful script loader like RequireJS can help in building a highly modular systems or web applications.

Reference:

MV* Framework

MV* frameworks have several advantages like defined framework and pattern but one of the best advantages, in my humble opinion, is organization. These frameworks allow us to tame the beast that is spaghetti code. For the purposes of enterprise development, there are several options out there. I have had personal experience with a few but a list of top 4 frameworks (once again in my humble opinion), would be something like this:

  • BackboneJS (for large applications, one should consider backbone layout manager)
  • KnockoutJS
  • AngularJS
  • EmberJS

With these frameworks, a selection of a templating tool is necessary. With BackboneJS and its hard dependency on underscoreJS, Underscore’s templating can be used. For more advanced templating, HandleBar and Mustache should be considered.

Reference:

Pre-processors

There are several pre-processors available for different aspects of front end development.

CSS

For this aspect, on the top of the list are two main pre-processors, LESS and Sass CSS. A lot of people select LESS because of the adoption of Twitter bootstrap. I am bigger fan of Sass CSS, because it is being maintained more often. Sass CSS also is adding more necessary features.

JavaScript

CoffeeScript being the most popular in this area has a huge following. In the development community, the use of CoffeeScript is divisive, some people really love it and some really hate it.I have used CoffeeScript and see the advantages of using it but I do not have any strong feeling for or against it. Let’s not forget TypeScript for those fans of .NET.

HTML

In this area, HAML and Jade are in the forefront. These tools although help with easy HTML writing.

Reference:

No matter the size of the project, a well structured and well written application along with its success may result in a  demand for expansion which is why every code should be written with scalability in mind. These technologies were considered with a scalable, maintainable and well-documented enterprise level architecture in mind.

As a result of this article, I have created a github repository with all these technologies (well most of them) incorporated. Please refer to https://github.com/kianoshp/node-boilerplate for more installation.


Why I chose Sass

Learning to appreciate the advantages of using pre-processors like Sass CSS in my work flow was not very hard for me. At times the challenge has been convincing others of the advantages of Sass and at times it can be divisive. A pre-processor is a simple tool that will provide some of the following advantages:

  • Smooth some of the harsh edges and create code frameworks  i.e. consistent code patterns
  • Extends the current process further by adding needed and missing features

A pre-processor like Sass does both.

My introduction to Sass was in 2009 during an interview for a job. During this interview, the interviewer asked me if I knew of Sass. I did not. However after the interview, I googled it and was introduced to the world of sass-lang.com. After the 5 minutes that it took to install it on my Mac (Sorry PC users, it might take 10 minutes for you), I was up and running. I played around with all its features and before I knew it, I was hooked.

In future projects, I was introduced to other CSS specific pre-processors like LESS, Stylus, and Closure Stylesheets. There has been certain feature sets that have made me gravitate back to Sass. Here are some of those features (I have used some code example from a real project) :

The Basics

All CSS pre-processors are built on the DRY (Don’t Repeat Yourself) principle. On that basis they all have the following features:

  • Variables
  • Import
  • Mixins
  • Functions
  • Selector Inheritance

Variables, Import, and Mixins are basic features that were my first foray into Sass and all by themselves have added quite a punch in this application.

CSS is a great language allowing designers and developers to improve the presentation layer. But until the introduction of pre-processors like Sass it has been a static language that uses its cascading feature to dynamically override styles and apply them to the presentation. With the introduction of Sass, DRY principles were added to CSS and therefore extending its features.

So let’s dive into some code and learn about Sass. The following is an example of a simple CSS. On one of the projects that I have been working on, I needed to create a header for sections of the site. This header will have a linear gradient background and white colored text.


/*This is a variable for the primary color of the side*/

$primary: #00096E;

/*primary grey color to be used throughout the site*/

$greyColor: #E0E0E0;

/*This is an example of a mixin that will create a linear gradient. The advantages of using this is

that we do not have to write the multiple vendor prefixed CSS repeatedly. And code maintenance is easier.*/

//this mixin will create a linear-gradient. The parameters passed here are:
//$pos: position of the gradient which defaults to top but can take bottom, left, or right
//$G1-G10: these allow for 10 color stops values, color and length/percentage
//$fallback: this is the fallback color that will be used for older browsers, if this parameter
//is not provided then the first color stop is used.
@mixin linear-gradient($pos, $G1, $G2: false,
 $G3: false, $G4: false,
 $G5: false, $G6: false,
 $G7: false, $G8: false,
 $G9: false, $G10: false,
 $fallback: false) {

 // Detect what type of value exists in $pos
 $pos-type: type-of(nth($pos, 1));

// If $pos is missing from mixin, reassign vars and add default position
 @if ($pos-type == color) or (nth($pos, 1) == "transparent") {
     $G10: $G9; $G9: $G8; $G8: $G7; $G7: $G6; $G6: $G5;
     $G5: $G4; $G4: $G3; $G3: $G2; $G2: $G1; $G1: $pos;
     $pos: top; // Default position
 }

 $pos: unquote($pos);

$full: $G1;
 @each $g in $G2, $G3, $G4, $G5, $G6, $G7, $G8, $G9, $G10 {
     @if $g != false {
         $full: $full + ',' + $g;
     }
 }

$full: unquote($full);

 //If using COMPASS uncomment the line below and remove line 82 - 89
 //$full: compact($G1, $G2, $G3, $G4, $G5, $G6, $G7, $G8, $G9, $G10);

 // Set $G1 as the default fallback color
 $fallback-color: nth($G1, 1);

// If $fallback is a color use that color as the fallback color
 @if type-of($fallback) == color {
     $fallback-color: $fallback;
 }

background: $fallback-color;
 background: webkit-gradient(linear, $full);
 background: -webkit-linear-gradient($pos, $full);
 background: -moz-linear-gradient($pos, $full);
 background: -ms-linear-gradient($pos, $full);
 background: -o-linear-gradient($full);
 background: unquote("linear-gradient(#{$full})");
}

The above mixin is courtesy of Thoughbot’s Bourbon mix which has quite an extensive collection of Sass mixins and functions.

Functions

Sass comes with several built in functions. These are functions that are commonly used and they fall in the following categories:

  • RGB functions
  • HSL function
  • Opacity functions
  • Other Color functions
  • String functions
  • Number functions
  • List functions
  • Introspection functions
  • Miscellaneous functions

Aside from the built-in functions, custom functions can also be created.


.main-header {

    @include linear-gradient(top, $primary, lighten($primary, 20%));
    color: white;
    display: inline-block;
    font-size: rfs(36);
    margin-left: 20px;

}

In this example, we are taking advantage of built-in color functions by passing the primary color and a 20% percent lighten primary color to our linear gradient mixin. We also are using a custom function that we have created to calculate the pixel font size in em, for a more responsive approach. Here is the detail of that function:


// ==|===Responsive Font Size calculator====================
// Function that will calculate the responsive font size
// return the em value to be used.
// =========================================================*/
@function responsiveFontSize($fontSize: $defaultBrowserSize, $isIE: false) {
    @if $isIE {
        @return (($fontSize/$defaultBrowserSize) - 0.02) + em;
    } @else {
        @return ($fontSize/$defaultBrowserSize) + em;
    }
}
@function rfs($fontSize: $defaultBrowserSize, $isIE: false) {
    @return responsiveFontSize($fontSize, $isIE);
}

For more information on functions, refer to the Sass documentation.

Selector Inheritance

This feature is one of the best features of Sass and one of the least used. This feature allows the user to think of the CSS and its features holistically and ensure the proper relationship among all the presentation elements.

For example there are times that one class will encompass most of the styles needed however there will an addition of other classes that will include not the styles of the more general class but also some of its own. For example, in our code above we have a ‘main-header’ class. Now we want to create sub headers:


.main-header {

    @include linear-gradient(top, $primary, lighten($primary, 20%));
    color: white;
    display: inline-block;
    font-size: rfs(36);
    margin-left: 20px;

}

.sub-header {
    @extend .main-header;
    @include linear-gradient(top, $secondary, lighten($secondary, 15%));
    font-size: rfs(24);
}

In this example, we inherited all the styles from ‘main-header’ and over-wrote the linear gradient with a different color and reduced the size of our font. And the output will look something like this:


.main-header, .sub-header {
    background: #00096e;
    background: webkit-gradient(linear, #00096e,#0011d4);
    background: -webkit-linear-gradient(top, #00096e,#0011d4);
    background: -moz-linear-gradient(top, #00096e,#0011d4);
    background: -ms-linear-gradient(top, #00096e,#0011d4);
    background: -o-linear-gradient(#00096e,#0011d4);
    background: linear-gradient(#00096e,#0011d4);
    color: white;
    display: inline-block;
    font-size: 2.25em;
    margin-left: 20px;

}

.sub-header {
    background: #cfc35d;
    background: webkit-gradient(linear, #cfc35d,#e0d998);
    background: -webkit-linear-gradient(top, #cfc35d,#e0d998);
    background: -moz-linear-gradient(top, #cfc35d,#e0d998);
    background: -ms-linear-gradient(top, #cfc35d,#e0d998);
    background: -o-linear-gradient(#cfc35d,#e0d998);
    background: linear-gradient(#cfc35d,#e0d998);
    font-size: 1.5em;
}

For a more comprehensive example of selector inheritance read this article by Thomas Reynolds.

Placeholder Selectors

Placeholder selectors follow the guideline of selector inheritance with one major improvement, they are silent until needed. A placeholder selector is a series of styles that are created for when there is situation where it is needed. If it is not extended, it will not be compiled to the final css output. If it is extended then the resulted styles will be in the output but the placeholder selector will not be in the compiled css. If we follow the example above, then the code will look like this:


%header-setup{
 color: white;
 display: inline-block;
 margin-left: 20px;
}

.main-header {
 @extend %header-setup;
 @include linear-gradient(top, $primary, lighten($primary, 20%));
 font-size: rfs(36);
}

.sub-header {
 @extend %header-setup;
 @include linear-gradient(top, $secondary, lighten($secondary, 15%));
 font-size: rfs(24);
}

We placed the portion of the styles common to both classes in a placeholder selector and named it header-setup. The output of the code looks like this:


.main-header, .sub-header {
 color: white;
 display: inline-block;
 margin-left: 20px;

}

.main-header {
 background: #00096e;
 background: webkit-gradient(linear, #00096e,#0011d4);
 background: -webkit-linear-gradient(top, #00096e,#0011d4);
 background: -moz-linear-gradient(top, #00096e,#0011d4);
 background: -ms-linear-gradient(top, #00096e,#0011d4);
 background: -o-linear-gradient(#00096e,#0011d4);
 background: linear-gradient(#00096e,#0011d4);
 font-size: 2.25em;

}

.sub-header {
 background: #cfc35d;
 background: webkit-gradient(linear, #cfc35d,#e0d998);
 background: -webkit-linear-gradient(top, #cfc35d,#e0d998);
 background: -moz-linear-gradient(top, #cfc35d,#e0d998);
 background: -ms-linear-gradient(top, #cfc35d,#e0d998);
 background: -o-linear-gradient(#cfc35d,#e0d998);
 background: linear-gradient(#cfc35d,#e0d998);
 font-size: 1.5em;

}

Object Oriented CSS (OOCSS)

Sass allows for a better framework for the implementation of OOCSS. If you are unfamiliar with OOCSS, Nicole Sullivan‘s answer to writing a well structured, efficient and performant CSS; here are a few resources:

Combining Sass and OOCSS principles make for a great way to write CSS. Here are some great articles in this regard:

Conclusion

Sass is a great that will enhance and improve upon CSS. If you have any reservations about using Sass, just experiment with it especially with the SCSS extension which allows you to use regular CSS in their along side with all the features of Sass. Cheers.


Why are preprocessors so divisive?

The genesis of this post is from a disagreement between me and a co-worker on the use of Sass CSS. This was during a project where as the UI Architect, I had decided on using Sass CSS. After a designer was brought on board, he did not want to use Sass. The discussion went something like this:

  • Designer guy: I am not familiar with Sass CSS
  • Me: Here is some information on it.
  • Designer guy: Compile my CSS? I don’t want to compile my CSS.
  • Me: Just use the ‘watch’ feature
  • Designer guy: I can’t debug my CSS in the browser.
  • Me: Use FireSass (For Firefox only)
  • Designer guy: I don’t want to use Sass CSS
  • Me: WE ARE USING SASS
  • Designer guy: Sass is just a fad
  • Me: We are using Sass

Multiple meetings were held that followed the same pattern as above. Looking back, I wish the discussions had gone a different way. Not in the sense that who was right or wrong but in the sense that it  could have been handled better. Introspectively, I could have done better.

Later on at the Backbone Conference in Boston, there were a couple of presenters that made statements like “CoffeeScript, you either love it or hate it”. This got me thinking, why should that be? Why are we in such polarized opinions when it comes to pre-processors in front end development? We are not the US Congress or the Senate for that matter. This got me thinking and started me on a path to find a peaceful solution to this issue.

Can you define pre-processors please?

In researching for this blog, I looked up the word pre-processors and found a lot of information. Wikipedia defines it as:

“In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessedform of the input data, which is often used by some subsequent programs like compilers. The amount and kind of processing done depends on the nature of the preprocessor; some preprocessors are only capable of performing relatively simple textual substitutions and macro expansions, while others have the power of full-fledged programming languages.”

By this definition, any work done on the code before compilation is the job of the preprocessor. There are two types of preprocessing:

  1. Lexical: This is typically macro substitution, text inclusion, conditional compilation, etc…
  2. Syntactical: Syntactical preprocessing’s role is to transform syntax trees according to user defined rules.

In the realm of front end development, most of the pre-processing tools are of the syntactical type. However stepping out of the computer science field, preprocessing exists in many areas of our lives. Couldn’t any encryption or decryption of code be considered as a preprocessor to gaining the underlying information. When a court stenographer types all the information in the court, wouldn’t that be considered a form pre-processing? How about short hand notes?

What tools are available?

In front end development, there has been an increase in the number of preprocessing tools thereby causing a bit of a polarized attitude towards them, not just whether to use any preprocessing tools but also which one. The tools that are available are as such:

  • HTML
    • HAML: (HTML Abstraction Markup Language) is a lightweight markup language that is used to describe the XHTML of any web document without the use of traditional inline coding. It’s designed to address many of the flaws in traditional templating engines, as well as making markup as elegant as it can be.
    • Jade: Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for nodehttp://jade-lang.com/
    • Zen-coding: In this post we present a new speedy way of writing HTML code using CSS-like selector syntax — a handy set of tools for high-speed HTML and CSS coding. It was developed by our author Sergey Chikuyonok.
  • CSS
    • Sass/Compass: Sass is an extension of CSS3, adding nested rulesvariablesmixins,selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin. Compass is an open-source CSS Authoring Framework.
    • LESS: extends CSS with dynamic behavior such as variables, mixins, operations and functions. LESS runs on both the client-side (Chrome, Safari, Firefox) and server-side, with Node.js and Rhino.
    • Stylus
  • JavaScript
    • CoffeeScript: CoffeeScript is a little language that compiles into JavaScript. Underneath all those awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.
    • IcedCoffeeScript: IcedCoffeeScript is a superset of CoffeeScript. The iced interpreter is a drop-in replacement for the standard coffee interpreter; it will interpret almost all existing CoffeeScript programs.
    • Dart: Dart is a new web programming language with libraries, a virtual machine, and tools. Dart helps developers build structured modern web apps. Dart compiles to JavaScript to run across the entire modern web.
    • GWT: Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. GWT is used by many products at Google, including Google AdWords and Orkut. It’s open source, completely free, and used by thousands of developers around the world.

How to argue correctly about preprocessors

At the Boston Backbone Conference 2012, Andrew Dupont had a great presentation about “How to argue about JavaScript”. This was a result of the famous discussion about semicolons – between Douglas Crockford and the world. Andrew outlined some great strategies and tactics to use when having a discussion (which I will shamelessly steal).

A lot of the times, we enter a discussion holding steadfast to our position and we feel that if we budge even a little bit then we have lost. This is unfortunately mirrored in our political environment and may give us a slight albeit wrong justification.

In science it often happens that scientists say, ‘You know that’s a really good argument; my position is mistaken,’ and then they actually change their minds and you never hear that old view from them again. They really do it. It doesn’t happen as often as it should, because scientists are human and change is sometimes painful. But it happens every day. I cannot recall the last time something like that happened in politics or religion.

Carl Sagan

When entering a discussion, one should consider approaching it as a scientific discussion vs. a political debate. Here are some more tactics and guidelines.

Discussion goals and tactics

On August 20th 2012, after hearing Representative Todd Akin’s comments regarding ‘Legitimate Rape’ saddened me as an American and human being. So I decided to post my thoughts on Facebook:

Facebook Post 8/20/2012

What started as an attempt to be diplomatic while expressing myself, ballooned into a full fledged political discussion. What made it worst was a comment from a friend:

Facebook unnecessary response

The photo in question is this:

Family picture with statue of Lenin

This was just a landmark in Seattle and being a proper tourist, we decided to take picture with it. That’s all. However this is an example of how discussions can get out of hand. In our community, the development community, we have plenty of vitriolic discussions. Let’s not forget the Semicolon war of 2012 or the selective tragedy of 2008.

I try, everyday I try to better myself especially when it comes discussions like this. The following are some of the tactics that I use in order to improve (these are mostly excerpt from the book “Getting to Yes negotiating agreement with giving in” by Roger Fisher and William Ury).

Goals of an argument

An argument/discussion has three goals:

  • It should produce a wise agreement, if possible
  • It should be efficient
  • It should not damage the relationship between the parties

Looking back at my interaction with “Designer guy”, I should have outlined and presented the reasons behind the use of Sass better or tried to reach a compromise for example let’s try it out for a while (a week or two) and re-visit this discussion then.

Tactics for an argument

  • Separate the people from the problem
  • Focus on interests, not positions
  • Invent options for mutual gain
  • Insist on objective criteria

In my example, I should have outlined our goals e.g. better development methods which is also a common goal and common interest.

Discussion preparation

When entering a discussion prep yourself in the following manner:

  • Retain the willingness to be convinced
  • Imagine where others are coming from
  • Account for your own taste
  • Account for your own emotions

Take a deep breath

When in a discussion follow these rules:

  • Be nice
  • Speak with surgical precision
  • Be honest in your characterizations
  • Don’t rise to the bait of others vitriol

If you see me taking a deep breath and counting to 10 (in my head), don’t take it personally.

Conclusion

I consider myself a work in progress when it comes to civil disagreements. However there will be times that one will have to walk away from a discussion. Don’t be afraid to do that, time will sort out the right from the wrong.

Further Reference


Journey Through MVC Architecture Using KnockoutJS

Up until two years ago, I had not idea of any MVC framework; however I knew that my front end development needed organization and structure. My first introduction to an MVC framework was JavaScriptMVC. I played around with it and implemented some of its organizational structure in the project I was working on. My second dive into the JavaScript MVC jungle was a 5 minute lightning presentation by Tim Branyen on Backbone at a meetup (if you know Tim and know how fast he can talk, then you will understand when I say there was a vast amount of information in that 5 minute talk). Coming out of that meetup and walking back with a fellow developer, he told me about KnockoutJS. I was eager to try out some of these frameworks on my next project.

The opportunity came up on my next project with MIT where I inherited a website in dire need of structure and organization. This is where my previous research paid off and I choose KnockoutJS to implement and this is what I learned in the process.

What does MVC mean for Front End Development?

When it comes to development, there are several design patterns and the MV* frameworks are examples of one design pattern. There is the all familiar MVC and there is also MVP and MVVM. Nevertheless, all these frameworks have similar baseline structures with minor differences. For simplicity sake, I will concentrate on MVC framework.

“The idea behind [MVC] is to make a clear division between domain objects that model our perception of the real world and presentation objects that are the UI elements we see on the screen…Domain objects should be completely self contained and work without reference to the presentation, they should also be able to support multiple presentation, possibly simultaneously.”

Martin Fowler

  • Model: domain or structural objects representing the application’s state. If your application has data or logic, then you need a model. Your application can be broken down into different models for example users, photos, experiments, classrooms, etc… These models contain a state that will be displayed to the user  in the “View”.
  • View: Observes the model’s state and generates output for the user. This is generally the part of the application the user sees and it is our way of displaying the model to the user through markup and templates.
  • Controller: Translates the user input into operations on the model. As the user interacts in the “View”, the controller captures the interaction and updates the state of the “Model”. Subsequently the implementation of an observer pattern will update the “View” with the latest state of the “Model”.

The frameworks that support the MV* structure are numerous, here are a few options:

When should one choose one of these frameworks? Some people think that if your application reaches certain level of complexity, you should be using one these frameworks. I am of the humble opinion that, aside from informational websites that can be written with WordPress, Drupal, or simple HTML (and no backend or database interaction), should adopt an MV* framework. Many sites may start as simple applications but your simple application especially if successful will become complex and at that point it may be too late and more difficult to implement these frameworks.

One of the best tools to evaluate the different types of MVC frameworks is Addy Osmani’s TODO MVC site. This site shows you how to implement a simple todo application using different frameworks.

Benefits of Using a MV* Framework

  • Separation of concerns: This is the main goal of an MVC framework, to be able to separate the different working areas of the site into Model, View, and Controller.
  • Easier overall maintenance
  • Side by side development: This is a  benefactor of the separation of concerns which will allow developers to work side by side on different parts of the application with reduced over-stepping on each others work.
  • Organization: If you have had to trudge through as much spaghetti code as I have, then this will be your favorite benefit of these frameworks.

One thing to consider is that these frameworks are not a substitute for good JavaScript development. These frameworks will enhance your code, it could enhance good code or bad code; you pick.

MVVM

MVVM was originally defined by Microsoft for use with Windows Presentation Foundation (WPF) and Silverlight, having been officially announced in 2005 by John Grossman in a blog post about Avalon (the codename for WPF). It also found some popularity in the Adobe Flex community as an alternative to simply using MVC. In the MVVM framework, the “Model” and the “View” follow the definitions as stated above. The “ViewModel”, as the name suggests, is the go between the View and the Model. The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model. For example, the Model may contain a boolean value like isAvailable, it is up to the ViewModel to interpret that and display the correct information to the user.

Benefits of KnockoutJS

  • Declarative bindings: Easily associate DOM elements with model data using a concise, readable syntax
  • Automatic UI refresh: When your data model’s state changes, your UI updates automatically
  • Dependency tracking: Implicitly set up chains of relationships between model data, to transform and combine it
  • Templating: Quickly generate sophisticated, nested UIs as a function of your model data

Next Steps

In order to better understand KnockoutJS, I have created a tutorial creating a Flickr app. Creating this app will help in better understanding of the KnockoutJS.

References


KnockoutJS Flickr App Tutorial – Part I

To better understand how to implementation of KnockoutJS, I have created a tutorial which creates a Flickr application searching Flickr photos based on tag and displaying them. It also allows the user to view an enlarged version of the photo and add it to a favorites section. Here is Balsamiq mockup of the application:

Model

In this example the Model will contains the information/data for the application. In this case we have two types of data, Photo and Favorite. The Photo model will have the following structure:

  Photo = function(id, owner, title, farmId, serverId, secret, ispublic, isfriend, isfamily) {
    this.id = id;
    this.owner = owner;
    this.title = title;
    this.farmId = farmId;
    this.serverId = serverId;
    this.secret = secret;
    this.ispublic = ispublic;
    this.isfriend = isfriend;
    this.isfamily = isfamily;
  };

The Favorite Model is simply a collection of Photo models:

  Favorites = function(Photo) {
    return this.Photo = Photo;
  };

ViewModel

The ViewModel not contains the objects that will be used in the view but also the functions and interactions between the model and the view. The first step is to create observable objects. KnockoutJS has three types of observable objects:

  • Simple object
  • Function
  • Array Object

Here are some how the observables will be used in KnockoutJS:

// Simple object
var myViewModel = {
    personName: ko.observable('Bob'),
    personAge: ko.observable(123)
};

//Function
function AppViewModel() {
    this.firstName = ko.observable('Bob');
    this.lastName = ko.observable('Smith');
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
};

//Array
var myObservableArray = ko.observableArray();    // Initially an empty array
myObservableArray.push('Some value');            // Adds the value and notifies observers

Keep in mind that some browser do not support getters and setters so all ko.observable objects are functions In order retrieve a set value, one will have to use the following code:

myViewModel.personName(); //will display Bob

To change the value of a viewModel, you will implement in the following manner:

myViewModel.personName('Roy');
myViewModel.personName(); //will display Roy

In order to create the proper structure, the first step is the create the objects of the viewModel. Some of the time, these objects will mirror the model data that has been returned from the server. However there will be times where we will need to create an object reflecting not only the information displayed to the user but also to record the interactions with the user. In our application, we have created a photos object which contains arrays of ‘image’ objects. The ‘image’ object has the following structure:

  • Photo object: this is an instance of the Photo object created in model
  • Photo src: this is the source for our image to be retrieved from Flickr
  photoViewModel = {
    //Photos: will be an array of image objects which will contain
    //Photo object and photo src
    photos: ko.observableArray([]),
    //Favorites
    favorites: ko.observableArray([])
  }

As you can see, the ‘photos’ and ‘favorites’ objects are initialized as empty knockout observable arrays. This is all that is needed in order to initially render the page. Once the user searches for a certain tag i.e. cat, dog, table, etc.., we will fire off a request to Flickr to retrieve the images. In the viewModel, we also create functions


photoViewModel = {
 ... //Photos and Favorites object are here //Function that will retrieve all the photos based on the search tag
 //and place them in the photos viewmodel
 getPhotos: function(formElement) {
   var searchTag, that;
   //reseting the previous search results
   photoViewModel.photos([]);
   //getting the search tag
   searchTag = $(formElement).find('#search').val();
   that = this;
   $.getJSON(flickrURL + searchTag)
   .done(function(photoData) {
     return _.each(photoData.photos.photo, function(photo) {
       var image;
       image = {
         photoObj: new Photo(photo.id,
                             photo.owner,
                             photo.title,
                             photo.farm,
                             photo.server,
                             photo.secret,
                             photo.ispublic,
                             photo.isfriend,
                             photo.isfamily),
         photoSrc: that.createSrc(photo.farm,
                                           photo.server,
                                           photo.id,
                                           photo.secret,
                                           'thumbnail')
       };
       return that.photos.push(image);
     });
   });
 }
}

We also need a function that will create the src URL for the images for us.


//Function that will create a src URL to be retrieved from Flickr</pre>
createSrc: function(farmId, serverId, id, secret, size) { return 'http://farm' + farmId + '.staticflickr.com/' + serverId + '/' + id + '_' + secret + (size === "thumbnail" ? "_s.jpg" : "_n.jpg"); } 

To add a photo to the favorites, we simply take the photo object that the user has selected and add it to the favorites array. By simply adding the object to the array combined with the fact that the favorites object is bound to the DOM element on the view, the photo will appear in the designated area.

 //Function that will add the selected photo to the favorites viewmodel
 addToFavorites: function(id) {
   var currentPhotoObj, favoriteExists;
   //getting the photo object of the selected photo
   currentPhotoObj = _.find(photoViewModel.photos(), function(photo) {
     return photo.photoObj['id'] === id;
   });
   //Checking to see if the item exists in the favorites or not
   favoriteExists = _.find(photoViewModel.favorites(), function(favorite) {
     return favorite.photoObj['id'] === currentPhotoObj.photoObj.id;
   });
   //adding the photo object to the favorites list
   if (!favoriteExists) {
     photoViewModel.favorites.push(currentPhotoObj);
   }
 },
 

The remaining code will perform the following functions:

  • remove from favorites
  • Show larger image
//Function that will remove the selected photo from the favorites viewmodel
 removeFromFavorites: function(id) {
   return photoViewModel.favorites.splice(_.indexOf(photoViewModel.favorites(),
                _.find(photoViewModel.favorites(), function(favorite) {
                  return favorite.photoObj['id'] === id;
                })), 1);
 },
 //Function that will show the larger image in the a modal box
 showLargerImage: function(id) {
   var currentPhotoObj, imageSrc;
   currentPhotoObj = _.find(photoViewModel.photos(), function(photo) {
     return photo.photoObj['id'] === id;
   });
   imageSrc = photoViewModel.createSrc(currentPhotoObj.photoObj.farmId,
                                       currentPhotoObj.photoObj.serverId,
                                       currentPhotoObj.photoObj.id,
                                       currentPhotoObj.photoObj.secret,
                                       'large');
   $('body').modal({
     height: 'auto',
     width: 'auto',
     loaderImgSrc: 'img/loader.gif',
     showSpinner: false
   });
   $('body').modal('openModal');
     return $('body').modal('updateContent', $('</pre>
<img alt="" />').attr('src', imageSrc)); } }; 

Note that in this process, we are using underscore.js and jquery.modal.js (a jquery plugin that I wrote myself).

View

The view being the center where we display the model at its current state to the user and also give the user the ability to modify/update the model. This is the markup for the search box:

<header>
<h1>Photo Finder</h1>
<strong>Search for photos in Flicker using tags</strong><form data-bind="submit: getPhotos">
 <input id="search" type="text" />
 </form>
</header>

As you can see, we have bound the submit button to the ‘getPhotos’ function in our view model. This binding (for the submit button binding ensure that the button is in a form) will prevent the default submit action but also will allow you to use the form as a handler for the view model and perform the specific function needed. In our case, we use it to retrieve the Flickr photos and place them in our view model. Once the photos are retrieved, we add them to the photos object in the view model. Because the view model is bound to the DOM, therefore consumed by the ‘photos-template’. At this point, any changes made to the photos object in the view model will be reflected in the UI automagically.

</pre>
<div id="main">
<h4>Search Results</h4>

<hr width="81%" />

<div id="results" data-bind="template: 'photos-template'"></div>
...<script id="photos-template" type="text/html">// <![CDATA[
<ul class="clearfix">
 {{each photos}}
	<li>
<div class="imgResult"><img src="${photoSrc}" id="${photoObj.id}" alt="${photoObj.title}-    ${photoObj.owner}" title="${photoObj.title}" /></div>
<div class="tabs"><img src="img/fav-icon-sketch.png" width="40%" alt="add to favorites" data-bind="click: function() { addToFavorites(photoObj.id) }"/>
          <img src="img/enlarge-sketch.png" width="40%" alt="show larger image" data-bind="click: function() { showLargerImage(photoObj.id) }"/></div></li>
{{/each}}</ul>
// ]]></script>

Also please notice that we have not only bound the photos object to this markup/template but we have also bound a couple of ‘click’ events that will call the appropriate function, passing the the photo id. Similar treatment for the favorites section:

</pre>
<div id="favs">
<div class="header">Favorites<img src="img/fav-icon-sketch.png" alt="add to favorites" width="15%" /></div>
<div id="favorites" data-bind="template: 'favorites-template'"></div>
</div>
<h3>...<script id="favorites-template" type="text/html">// <![CDATA[
<ul class="clearfix">
 {{each favorites}}
	<li>
<div class="imgResult"><img src="${photoSrc}" id="${photoObj.id}" alt="${photoObj.title}-${photoObj.owner}" title="${photoObj.title}" /></div>
<div class="tabs"><img src="img/remove-sketch.png" width="40%" alt="add to favorites" data-bind="click: function() { removeFromFavorites(photoObj.id) }"/></div></li>
{{/each}}</ul>
// ]]></script>

Reference

Next Steps

Common complaint of KnockoutJS is the what seems like the mixing of javascript, data-bind attributes, and markup. However KnockoutJS allows you to create custom bindings. One option to combat the overly tied application logic to the view is to create a custom binding similar to CSS classes. Ryan Niemeyer has suggested this procedure. In part II of this tutorial, we will tackle this option.


Follow

Get every new post delivered to your Inbox.

Join 196 other followers