About callbacks

March 25th, 2012

Let’s talk about callbacks, people seem to get terrified by them, because they see something like this:

var mysql = require('mysql'),
    db = mysql.createClient({
        user: 'root',
        password: 'root'
    }),
    id = 1;
 
db.query('USE mydb', function (err) {
    //some code here
    db.query('SELECT * FROM whatever WHERE id=?', [id], function (err, foo) {
        if (foo) {
            //some other code
            db.query('UPDATE whatever SET bar=?', [foo.bar], function (err) {
                db.query('INSERT INTO someothertable (sometime) VALUES (NOW())', function () {
                    //some code
                    console.log("It's done");
                });
            });
        }
    });
    //more code
});

This has the potential to turn into hard to understand spaghetti code. But we don’t have to write it like this, we don’t have to inline every function we can simply name them instead.

var mysql = require('mysql'),
    db = mysql.createClient({
        user: 'root',
        password: 'root'
    }),
    id = 1;
 
function init(fn) {
    db.query('USE mydb', fn);
}
 
function fetch(id, fn) {
    db.query('SELECT * FROM whatever WHERE id=?', [id], fn);
}
 
function checker(err, foo) {
    if (foo) {
        //some other code
        update(foo.bar);
    }
}
 
function update(bar) {
    db.query('UPDATE whatever SET bar=?', [bar], function (err) {
        db.query('INSERT INTO someothertable (sometime) VALUES (NOW())', function () {
            //some code
            console.log("It's done");
        });
    });
}
 
init(function () {
    fetch(id, checker);
})

We could also put this in a module or wrap a (pseudo) class around it if we wanted to. The main point is that we don’t have to nest inline callbacks to get the job done, we can name them.

It’s all about the style

March 22nd, 2012

This is how many people like to write code:

<?php
/*
 * Enterprise class backtrack 
 */
 
class Backtrack {
 
    private $values;
    private $stack = array();
    private $results = array();
 
    public function __construct($values) {
        $this->values = $values;
    }
 
    public function search() {
        $this->results = array();
        $this->doSearch();
    }
 
    public function getResults() {
        return $this->results;
    }
 
    private function doSearch() {
        if ($this->reject()) {
            return;
        }
 
        if ($this->accept()) {
            $this->results[]= $this->stack;
        }
 
        $ostack = $this->stack;
 
        foreach ($this->values as $value) {
            $this->stack = $ostack;
            $this->stack[]= $value;
            $this->doSearch();
        }
    }
 
    private function accept() {
        return count($this->stack) > 0;
    }
 
    private function reject() {
        return count($this->stack) > count($this->values);
    }
 
}
 
$bt = new Backtrack(array(1, 2, 3));
$bt->search();
var_dump($bt->getResults());

This is how I prefer to write code:

<?php
/*
 * Functional Backtrack
 */
 
function backtrack_accept($values, $stack) {
    return count($stack) > 0;
}
 
function backtrack_reject($values, $stack) {
    return count($stack) > count($values);
}
 
function backtrack($values, $stack = array()) {
    $results = array();
 
    if (backtrack_reject($values, $stack)) {
        return $results;
    }
 
    if (backtrack_accept($values, $stack)) {
        $results[]= $stack;
    }
 
    foreach ($values as $value) {
        $nstack = $stack;
        $nstack[]= $value;
        $results = array_merge($results, backtrack($values, $nstack));
    }
 
    return $results;
}
 
var_dump(backtrack(array(1, 2, 3)));

What do you prefer?

New Blog theme

May 8th, 2011

I started integrating the blog to the rest of my site, it really looked awkward that it stoot out from it. Now it will blend in, also it will be a lot faster. The new theme is still missing a lot of stuff that I will carefully add back in time.

My goals are:

  • Be fast
  • Use jQuery UI
  • Be HTML5

I am also considering cleaning up my categories, it’s a mess.

If the new theme will be fully complete I may consider publishing it in the future.

Why are you still using XHTML?

March 30th, 2011

I am puzzled by the fact that some people still use XHTML, the HTML-clone which was born, because XML fans couldn’t bare to write <br> and instead desired to write <br />.

The difference between XHTML and HTML is that XHTML has a more complex doctype, forces self closing tags and has more strict validation rules that may have made sense back them but they don’t really make sense now.

XHTML promised interoperability with other XML languages, what it didn’t promise was browser support for them.

The latest release of XHTML that actually has browser support is from 2001, that’s even older than IE6.

Writing in XHTML is worthless if you do not validate it(XML in general is only useful if you actually plan to validate it), the problem is that both the validation rules and the validators are unreasonable also well-formed/academic markup will not guaranty browser support, it even makes it harder to support browsers because the strict rules make it hard to write hacks for lesser browsers. Because of this, most people who write XHTML don’t bother to validate it, which makes the whole thing dubious.

And there was XHTML 2.0, which shows that the XHTML group still doesn’t understand how browsers and users work, they dropped backward compatibility ignoring millions of users and the fact that old browsers don’t upgrade magically overnight. Because of these XHTML 2.0 failed misserably.

We are now in 2011, we have HTML5, which can optionally act as XML if the developer wants enforced well-formed-ness(if the browser actually cares to enforce it), it supports both <br> and <br/>, the developer decides the usage, which is good because nowadays mashups are very common and separate syntaxes make this painful.

The HTML5 doctype is much shorter while providing access to the ‘future’ elements and backward compatibility all the way back to IE6.

Despite all this, why are some people and frameworks still using XHTML 1.x?

My first github repository

March 20th, 2011

I have been playing around with git for a while, I have been mainly using it synchronize my projects between my laptop and my desktop.

Now I have created a small templating engine in PHP and I decided to publish it on github.

The awesome thing about github is that everything is well documented and easy to use once it is set up correctly.

Anyone who is interested can fork my project at: https://github.com/istvan-antal/MicroTemplate

What they don’t teach you in (W3)school: JavaScript variable scoping

January 27th, 2011

W3Fools is an interesting site I came across that highlights the wrong parts of W3Schools. While W3Schools is the most popular online resource for web standards, its content has a lot of serious flaws.

One such problem at W3Schools is variable scoping in JavaScript(w3schools page):

JavaScript has a global scope(global window object to be more precise), that is the place where all global variables go, usage of this must be minimized because in most pages there will probably be scripts from multiple sources, if everyone relies on the global scope, than sooner or later one script will get into conflict with another. The var keyword is not an optional decoration in JavaScript, if we leave out the var, then the global scope is assumed automatically. Here are some examples:

These functions declared global variables, therefore our local variable loses its original value:

something = 'first thing';
 
function foo() {
    something = 'foo';
}
function bar() {
    something = 'bar';
}
 
foo();
bar();
console.log(something); //'bar'

These functions declared local variables, no collisions have occurred here:

var something = 'first thing';
 
function foo() {
    var something = 'foo';
}
function bar() {
    var something = 'bar';
}
 
foo();
bar();
console.log(something); //'first thing'

W3Schools states the following too:

If you redeclare a JavaScript variable, it will not lose its original value.

While it may not cause an error now it is certainly not a good practice and could lead to confusion and maybe runtime errors in future versions of ECMA Script(JavaScript).

There are also other important facts about the var keyword that are not mentioned in W3Schools:

var is function scoped and not block scoped:

function test() {
    if (true) {
         var test = 3;
    }
}

works just like:

function test() {
    var test;
    if (true) {
         test = 3;
    }
}

Either way you will be able to access the variable test after the block. A better example might be:

for (var i=0;i&lt;10;i++) {
}
console.log(i); //10

The best practice to avoid confusion is to begin each function with a single var declaration and declare all variables in that single var declaration. JSLint can help you with that. And learning more about JavaScript is as easy as watching a couple of videos I outlined in one of my previous posts.

Update:
the best comment this article/issue received so far: http://www.reddit.com/r/web_design/comments/fa9hp/what_they_dont_teach_you_in_w3school_javascript/c1ejet7

Update 2: made the w3schools link weaker.

Update 3: added rel=”nofollow” to w3schools links.

Avoiding SQL

January 16th, 2011

I have been writing dynamic database-backed web applications since 2006, still whenever I fire up my IDE, I can’t help notice that the SQL in my code doesn’t feel natural, my IDE can’t parse it, because in essence, it’s a string that gets created on runtime. SQL itself can be pretty counter intuitive, it has poor support for complex data structures, one of it’s main weaknesses is that(to my knowledge) it can’t return nested structures. In terms of clarity, SQL doesn’t scale well, long SQL strings are really hard to understand.

In real life we have complex and nested data and we need to make our code as clear as possible. A common practice(MVC) is to put all the SQL into data access objects and use it’s API instead of raw SQL. I did just that I had most of my SQL in objects, what I found is that I kept repeating code and kept doing the same thing with every new data access object I made, but at least I always knew the purpose of the SQL queries, because they were encapsulated.

One day I kept hearing about NoSQL databases, they looked to offer something better but I ignored them because most hosting providers don’t support them. A while ago however I heard about object relational mappings(ORM), libraries which provide a native API on top of SQL. This sounded just like what I needed, something that could help eliminate the duplication I previously had with my data access objects.

I searched for an ORM written for PHP and I found Flourish ORM, after finding it I realized that this is what I needed all along. I can create a basic ActiveRecord in 3-4 lines of code, the only thing I need to specify is the database it maps to, the ORM layer reads the schema of the database and gives me dynamic methods that I can use instead of SQL.

//this is how we initialize
class User extends fActiveRecord
{
}
fORM::mapClassToTable('User', 'user');
//this is what we get
$user = new User();
$user->setName('Test user');
$user->setPassword('123456');
$user->store();

That’s it, I get similar methods for the rest of the database operations, one of the main benefits is that I no longer have to worry about string concatenation. I can override these methods at any time using standard OOP techniques. Of course this does not mean that I will never write SQL again, but I will write and maintain a lot less that I was used to. Another big advantage is that there is a standard API for data handling, if someone takes over my code, I could simply point to the Flourish documentation.

Web developer’s guide

December 9th, 2010

I decided to do a compilation of web based resources that help learn web developing. I have strictly sticked to resources that are available on the web for free. I tried to categorize them by skill level. This will probably get revised a lot, I am looking forward to suggestions. Nearly none of this is my own work and I may be biased towards certain authors.

Beginer

Google Code Uniersity is a really good place to start learning the basics of web developing, I recommend the following tutorials:

HTML, CSS, and Javascript from the Ground Up

CSS, HTML and Javascript

AJAX Tutorial

Advanced

YUI Theatre is one of the places that has a lot of interesting talks where a developer can learn more about how the web actually works and how a developer could improve things. These are the ones that I think web developers should watch:

A developer needs to fully understand JavaScript as a programing language.

Douglas Crockford – The JavaScript Programming Language part 1part 2part 3 and part 4 – this is a must view for every web developer, it really helps understand how JavaScript actually works and how we can program in it effectively.

The good parts of the language need to be learned.

Douglas Crockford - JavaScript: The Good Parts

A developer should understand that the browser’s DOM API is broken.

Browser Wars Episode II: Attack of the DOMs – Presented by the Silicon Valley WebBuilder, this event brought together Mike Shaver from Mozilla, Chris Wilson from Microsoft’s IE team, Håkon Lie from Opera, and moderator Douglas Crockford from Yahoo! to talk about the current state of the browser landscape. This video helps understand why is the web broken even today.

Douglas Crockford — An Inconvenient API: The Theory of the DOM

Using libraries is mandatory.

John Resig: “Advancing JavaScript with Libraries” part 1 and part 2 – Johen Resig is the author of jQuery. He talks about how JavaScript libraries work, what they do and how can they help a web developer do more and worrying less about how the DOM works.

Christian Heilmann — YQL and YUI: Building Blocks for Quick Applications

Beyond…

Those who want to create really heavy client side web applications need to aspire for quality.

Douglas Crockford: “Quality” – this can teach a programmer new ways to look at code and measure it’s quality.

Being cutting edge is also very important, if we want to have a future, we must be ready for it.

Brad Neuberg — Introduction to HTML5 – there are a lot of things that are already there and we can make use of.
Brendan Eich — ECMA Harmony and the Future of JavaScript

Speed is very important, it could mean the difference between success and failure, so being able to optimize successfully is a big win.

Joseph Smarr: “High-performance JavaScript: Why Everything You’ve Been is wrong
Nicole Sullivan — Design Fast Websites
Nicholas Zakas – Speed Up Your JavaScript

In terms of CSS a web developer needs to avoid bloating it.

Nicole Sullivan – Top 5 Mistakes of Massive CSS

Starting easy
http://ontwik.com/html5-2/paul-irish-on-html5-boilerplate/

JavaScripting is possible on the server side too, and it can be really powerful.
Ryan Dahl — Introduction to NodeJS
Douglas Crockford — Crockford on JavaScript — Scene 6: Loopage
Dav Glass — Using Node.js and YUI 3

Developers coming from other programing languages

JavaScript is a unique language, and can suprise developers coming from other languages.

C# developers should check out:
How Good C# Habits can Encourage Bad JavaScript Habits: Part 1
How Good C# Habits can Encourage Bad JavaScript Habits: Part 2 – False-y, Testing and Default Values, Comparisons, and Looping

Conditional JavaScript

October 20th, 2010

Having conditional comments and CSS references inside them is good, having conditional comments give the body or html element a class is better, but in my opinion having all this in a JavaScrip file is better.

First thing is to take this code:

var IE = (function() {
  var undef, v = 3, div = document.createElement('div'),
      all = div.getElementsByTagName('i');
  while (
      div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
      all[0]
  );
  return v > 4 ? v : undef;
}());

Now we have a reliable variable called IE which contains either undefined or the IE version. Now we can do real fun stuff with this:

/*IE support*/
if (IE==6) {
    $.getScript('lib/DD_belatedPNG_0.0.8a-min.js', function() {
        DD_belatedPNG.fix('img, .textInput, .apng,.picture-box-frame');
    });
}
 
if (IE) {
    $('html').addClass('ie');
    $('html').addClass('ie'+IE);
}

We can load IE specific hacks from the script tag without bloating the HTML header and we can also add CSS classes to top level elements without filling our HTML header with conditional comments. This is a really clean and flexible approach that doesn’t force you to make your header look like trash.

NoScript

NoScript people will simply tell you that: “If the user has JavaScript disabled this will not work”

According to Yahoo approx. 2% of the US visitors have JavaScript disabled and far less in other parts of the world. But let’s take the 2% for users who for some reason don’t have JavaScript enabled, and discard everyone but the IE users and we get a number that’s far less then 2%. This is highly dependent on the product but if I have to break the experience for less then 2% of my users for the benefit of the remaining 98%, I think I will go with it.

A lot of IE hacks(like PNG hacks) will not work without JavaScript anyway so the user will still have a broken rendering even if I put the conditional CSS in the HTML.

Disabled JavaScript myths

October 13th, 2010

A lot of people are debating on whether or not is it worth developing for users that have disabled JavaScript or not. I already talked about this, so instead I am gonna bust a few myths that are supposed to be reasons for disabling it:

1) Using JavaScript is insecure.

JavaScript is a programing language, not a security hole. Calling JavaScript a security hole is the same as calling any other programming language a security vulnerability. In fact JavaScript’s DOM environment is one of the few that makes a difference between user and non-user generated events on a very deep level.

2) JavaScript is a privacy threat.

JavaScript has nothing to do with privacy, cookies should be disabled for better privacy, but then very few login systems would actually work.

3) JavaScript saves bandwidth.

Well actually quite the opposite is true, while you do not download the JavaScript source files, you actually end up downloading a whole page on every interaction instead of partial page replacements with AJAX. Also JS files are cached so a lot of common knowledge on interaction could be cached, thus requiring only the least amount of information from the server.

I assume most users who disable JavaScript simply don’t understand it or have a computer and browser combination from the last millennium, or maybe simply feel to classy or old schoolish for this. I wonder how many of them leave Flash enabled…