Monthly Archives: June 2013

Introduction to Mustache.js

If you want to create an application that runs mostly in the users browser, you will have to render HTML in JavaScript. To do that efficiently, you should use a template framework. In my opinion, the best one you can currently use is mustache.js. Here are some examples:

Variables

var view = {
    name: 'Patrick',
    age: 19
};

var template = '{{name}} is {{age}} years old.';

var output = Mustache.render(template, view);

Output

Patrick is 19 years old.

 

Lists

var view = {
    name: 'Patrick',
    friends: [
        { name: 'Joel' },
        { name: 'Pascal' },
        { name: 'Tobias' }
    ]
};

var template = 'Here are {{name}}s friends: {{#friends}}{{name}} {{/friends}}';

var output = Mustache.render(template, view);

Output

Here are Patricks friends: Joel Pascal Tobias

 

True/False Switches

var view = {
    name: 'Patrick',
    hasCar: true
};

var template = 'This is {{name}}. {{#hasCar}}He owns a car.{{/hasCar}}';

var output = Mustache.render(template, view);

Output

This is Patrick. He owns a car.

 

If used correctly, this can be a huge help. Check out mustache.js on GitHub and a jQuery compatible version here. Happy coding.

C# Lambda Expressions: Quick Tutorial

In C#, there is a shortcut for anonymous methods called Lambda Expression. To understand Lambda, we first need to have a basic understanding of how delegates work.

Let’s assume we want to write a method that finds elements in a List<T> that match certain criterias. Those criterias can change between different calls of said method and for that we will need a delegate:

delegate bool matchesCriteria(int number);

static List<int> findInList(matchesCriteria doesMatchCriterias, List<int> list)
{
    var newList = new List<int>();

    foreach (var number in list)
    {
        if (doesMatchCriterias(number))
        {
            newList.Add(number);
        }
    }

    return newList;
}

We can call this method like this:

var outputList = findInList(delegate(int n) { return n < 5; }, list);

The first parameter is a new anonymous method that will be represented as 'doesMatchCriterias' in the 'findInList' method. What we are doing is basically creating a method that checks if a number is smaller than 5 and then returns true or false. If it's true, the 'findInList' method will add the number to a new list.

If we want to find all elements in a list that are not 9, we can use the exact same function since we've used a delegate:

var outputList = findInList(delegate(int n) { return n != 9; }, list);

Easy, right? Now a Lambda Expression helps us writing shorter anonymous delegates. Here is the last example written as a Lambda Expression:

var outputList = findInList(n => n != 9, list);

On the left-hand side of the Lambda Operator (=>) are the arguments for the delegate. The part on the right translates to a simple 'return n != 9'. We don't need the return keyword, because we only use one statement.

You can also use them in many methods provided by the .NET framework:

var outputList = list.FindAll(x => x < 6 && x != 15);

Summary

Lambda Expressions are shortcuts for anonymous methods and can be super useful. They were added in .NET 3.5 and can really clean up your code.

Difference between WHERE and HAVING in T-SQL Statements

Both clauses in SQL statements are filtering a specific output, but there’s a significant difference. Here’s what Wikipedia tells us:

A HAVING clause in SQL specifies that an SQL SELECT statement should only return rows where aggregate values meet the specified conditions.

Aggregate Functions are the following:

  • AVG
  • COUNT
  • FIRST
  • LAST
  • MAX
  • MIN
  • SUM

So HAVING clauses can only be used if you are using an aggregate function with a GROUP BY clause. I’ve set up a small table on MS SQL Server to try this out:

Name Wins
Toby 23
Toby 11
Lisa 16
John 4
John 7

Here is our SELECT statement for this table and its output:

SELECT Name, SUM(Wins)
FROM WinRecords
GROUP BY Name
Name Wins
John 11
Lisa 16
Toby 34

This grouped the results by the names of our entries. But what if we want to display entries with more than 10 wins? We can try using a WHERE clause:

SELECT Name, SUM(Wins)
FROM WinRecords
WHERE Wins > 10
GROUP BY Name
Name Wins
Lisa 16
Toby 34

That didn’t work as we expected it to. John has a total of 11 wins, so he should be displayed too. That’s because the WHERE clause runs before the aggregate functions, while HAVING runs after the aggregate values have been calculated.

Here’s the query with HAVING:

SELECT Name, SUM(Wins)
FROM WinRecords
GROUP BY Name
HAVING SUM(Wins) > 10
Name Wins
John 11
Lisa 16
Toby 34

Note: You can’t use aliases in HAVING clauses, that’s why I typed SUM(Wins) out.

This query would exclude everyone with less than 10 wins in total. Pretty cool, huh?

TDD in JavaScript with the Jasmine Framework

Test-driven development (TDD) is a simple process that helps you write better and more stable code. Here is how it works:

  1. Write a test for your new, currently unwritten class. Obviously, all tests will fail.
  2. Program the new class so it matches the requirements for your tests.
  3. Refactor the code.

You sure wonder what such a test could look like. Here is one, written in JavaScript with the Jasmine Framework:

describe('The regular expression for the date validation', function() {
  it('should not match any day &gt; 31', function() {
    expect(validateDate('2013/12/32')).toBe(false);
  });

  it('should not match 00 in the day part', function() {
    expect(validateDate('2013/01/00')).toBe(false);
  });
});

That’s it, you only need to remember this structure in order to write unit tests with Jasmine.

There are also other methods to check an output with ‘expect’. You can for instance expect a number to not be greater than Pi:

expect(output).not.toBeGreaterThan(pi);

Or just to be somewhat the same value as any number:

var pi = 3.1415926, e = 2.78;
expect(pi).toBeCloseTo(e, 2);

The second parameter of ‘toBeCloseTo’ defines the matching precision. There’s way more that you can do with this framework, you should check it out on GitHub. It also doesn’t rely on any other framework or browser.