Wednesday, October 8, 2014

Got to confess, I have not used strict mode in JavaScript at all until now. I was not even aware of it despite the fact that, a) it has been introduced as a new feature of ECMAScript 5 since 2009; b) It has become the de-facto standard in JavaScript coding; c) Quite some JavaScript Ninjas/gurus have written and endorsed it.

But now, I am in for using strict mode in JavaScript. Why? Because everyone should, because silly errors should be caught early instead of late, because accidental global variables should be stopped cold.

Yep, I would say, strict mode can handily prevent some late-night sleep-deprived accidents, or simply newbie I-do-not-know-type of mistakes.

Some of them are the following (and any of them can and will break your page):

 1) Accidental global variable

var answer = 42;
answer = "Thanks for all the fish...";

x = "The answer is " + 42; // "The answer is 42"
y = 42 + " is the answer"; // "42 is the answer"

2) Reference errors

var a;
console.log("The value of a is " + a); // undefined
console.log("The value of b is " + b); // reference error

 3) Duplicate object properties

 console.log({ a: 1, b: 2, c: 3, a: 1 });

 4) Duplicate function parameter names

 function testMe(testa, testb, testc, testa) {

 5) Delete unqualified names

 var testObj = {
    a: 1,
    b: 2,
    c: 3
 delete testObj;//error 

Though you can still go about to remove the property c from the tsetObj 

delete testObj.c; // will be ok here
console.log(testObj.c); // undefined

 6) Evil eval

 Everyone knows that eval is evil, so do not use it, declare it, assign it, ... simply delete that word from your Javascript lexicon.

 // All generate errors...
//(directly lifted from Jon Resig's article: ECMAScript 5 Strict Mode, JSON, and More)

obj.eval = ... = eval;
var eval = ...;
for ( var eval in ... ) {}
function eval(){}
function test(eval){}
new Function("eval")

Trying to create a new variable using var won't work

eval('var x=testObj.a;');

References Here (Or simply google):

Strict Mode
JavaScript Use Strict

Thursday, October 2, 2014

So onward and fast forward from running through one learn-to-code app to another, I finally decided to go straight back to my home camp, the JavaScript camp.

The whys

Why not? For all the good reasons, convenience, resources, usefulness ... why not?

In this coding kingdom, nothing is more convenient and ubiquitous than JavaScript, the language of the web. Who does not use the web? Even on your phone. Even some of your favorite apps.

Resources? There is more libraries, frameworks than you can count.

Comfortable? Yes, I am utterly at home with JavaScript.

Useful? Yes, I am done with building just another play thing living in someone else website.

Yet another back story is that, unlike a lot of game kids, my kids are not so deeply immersed in the game culture. Rather, they are utilitarian; Unlike me, who always checkout and use whatever is out there, my kids want to build their own tools. For example, they want to build a student bean counter so the teacher can easily track at any given time on any given day, which kid is missing; they want to build a Knock-knock-who-is-there joke factory.

Now, they want to build a star/sticker chart, which gives out (online) stickers whenever someone does a good (or not so goo) job , for example, playing violin.

So there we go.

JavaScript can do math homework

Honestly, coding does look daunting. So the first thing I tried is lure my kids by showing off some of the awesome homework-checking capabilities of JavaScript. Like the following. Using FireBug console.

Ok, it is not quite JavaScript yet, but by using FireBug, the little adds-on for Firefox, I gave her a glimpse of JavaScript

Get in touch with basic html tags

A little quick math quickly lost its shine. So I set out to show the basic html dress code, tags like <p>, <img> and the basic html page structure, head, body, title, etc. Luckily for me, I have Visual Studio, so creating a page is a breeze. The next thing, adding some tags, <p>, <img>. So quickly we have a page (ugly it is) set up that have a image from Google, and some text goes with it.

My daughter was having trouble remembering put the text inside of the <p> tag.

Introduce the concept of array

So far so good. My daughter was mildly interested and amused to see her own page actually come alive!

Yet, we need a lot of knock knock jokes. So I have her to drop more <p>, <img> It was getting very very boring and error prone, so obviously, computer should be more fun and intelligent than this.

So let's see if we can handle an array.

Every programming term sounds so alien. She does not get the name variable or array.

What is an array?
Eh, Emma, an array is a collection of things. Ok?
What does it do?
Eh, it let you put things together, then you can use a loop to go through them one by one.
What is a loop?
A loop is just a loop ...

I am always a person who is short at words, now I am out of words.

No matter. Let's build an array anyway.

In JavaScript, you put similar things inside a pair of square bracket. Like this:

var knockknockJokes = [
            { who: 'lettuce', whoIs: 'lettuce in!', image: "" },
            { who: 'figs', whoIs: "Figs the doorbell, it's broken!", image: "" },
            { who: 'Avenue', whoIs: 'Avenue heard this joke before?', image: "" },
            { who: 'Aunt', whoIs: "Aunt you glad Granny's gone ?", image: "" },
            { who: 'Orange.', whoIs: 'Orange you going to let me in?', image: "" }

It took more explanation, the object inside of the array, the properties inside of the object, etc. I wish i knew better, more kids-friendly words.

Anyway, the array is done. Let's spill all of our knock-knock jokes.

I wrote the loop for her. And our page is done. We are happy.
The Knock Knock page

Next time, I will tell how I get her to know a bit of JavaScript function, the very core of JavaScript.

Saturday, September 20, 2014

Trend dictates that everyone needs to code and be able to code. Who does not want to be the next Mark Zuckerberg or Larry Page, or at least, their employees?

There is an abundance of resources and teaching initiatives. (backed by Mark  Zuckerberg, Bill Gates, etc. etc., anyone who is somebody across all social walks) had some online tutorials interspersed with inspirational videos;

Khan Academy has dedicated computer programming courses where you can clone and create your JavaScript project;

MIT has Scratch, where kids can drag and drop coding blocks, cartoon characters, video/audios and build simple video games, animations, or simply tell a story.

There are all sort of coding games, which are more game than coding, that try to introduce the ideas about functions, loops, variables, and some logic training. My favorite is Kodable.

As a professional programmer and a mom who also eagerly wants to pass on some of the coding skills to my kids, I have ambiguous feelings about all of the programs I have tried with my kids, and I have very limited success getting my kids interested.

For example, Khan academy has simple ideas about teaching kids drawing with JavaScript. With that, you need some fine sense of coordinates. It is supposedly a very visual task however it requires you to plot all the spacial points out of thin air. My kids quickly gave up trying to draw a duck with a plump body and 2 yellow eyes. is fine too, it teaches basic programming concepts such  as Conditionals, Loops, functions, It is all done in some format of half gaming. Instead of instant feedback from video games, you point, you shoot, something happens, With games, you stack up your instructions, then hit run to see if your angry bird will get the pig while also evade a potential disaster.

As a matter of fact, most of current coding games are done in this fashion.

Kodable, where fuzzes run through a maze collecting coins; Tykner, has different set of games, Dragons and Firefly; Candy Catcher, etc,, etc.. I like Kodable a lot, it has cute and simple interface, very helpful and non-intrusive instructions and contextual hints, very clear objective and path of execution.

However, Tykner, I found it very annoying. It is hyper-active, lacking clear instructions, sometimes logically confusing. Do you jump on the candy, or jump over the candy in order to eat it?

Then there is Scratch from MIT, where kids or anyone can drag and drop instructions, sprites (images) and start building animated stories. It is very popular and admired for its versatility, and people have created millions of projects with it. Some of the projects are quite fun.

I tried Scratch with my kids and we created a few projects. Still, a lot of things feel very retro. the sprite set is very old fashioned, you need to watch some tutorials to realize how to coordinate your sprites, it is not easy to create simple variable and make them behave dynamically. To master Scratch, the effort is no less than a full-blown language. Make everything graphic on the surface may seem to have simplify coding, but in the end, it actually creates more obstacles and complexities.

That is why I eventually went to JavaScript.

Until next time.

Sunday, July 6, 2014


Dapper is an object-relational mapping (ORM) solution for the Microsoft .NET platform. It is written for and used by stackoverflow. It has the signatures of a stackoverflow baby, hugely popular, no-bullshit/lightweight, effective and efficient, stellar performance.

We have been using Dapper for a couple of years. We love it, for its simplicity and performance. It is so simple, whether we do select, insert or update, whether we use stored procedures or ad-hoc sql.

using (var connection = new SqlConnection(myConnectionString))
                const string sqlStatement = @"select client_id As Id, client_name As Name from dbo.client with(nolock) ";
                return connection.Query(sqlStatement);

.NET async 

.net 4.5 came out about 2 years ago, and asynchronous programming with async and await is one of the big features. async/await allows you to define a Task that you can await on, and then continue execution once the work is done, all without blocking the calling thread unnecessarily. async and await operations took away the programmatic complexity from programmers, however, under the hood the compiler still does the heavy lifting of setting up a waiting context/state machine so a task can get back to exactly where it has begun.

 The overhead of async/await in NET 4.5 demonstrates that "Despite this async method being relatively simple, ANTS Performance Profiler shows that it’s caused over 900 framework methods to be run in order to initialize it and the work it does the first time that it’s run."

 It is agreed upon that async/await should be limited to only I/O heavy operations, web access, working with files, working with images.

How about database calls? Turned out database calls are by nature blocking. It blocks the calling thread even if you stamp your method as async and use the await keyword.

 To allow asynchronous database queries and other crud operation, dapper added a set of QueryAsync methods using .NET Framework 4.5's Task-Based Asynchronous Pattern. Under the hood, the asyn dapper methods uses connection.OpenAync, executeReaderAsync to allow connections to be opened and queried in asynchoronous mode.
      public static async Task> QueryAsync(this IDbConnection cnn, CommandDefinition command)
            object param = command.Parameters;
            var identity = new Identity(command.CommandText, command.CommandType, cnn, typeof(T), param == null ? null : param.GetType(), null);
            var info = GetCacheInfo(identity, param);
            bool wasClosed = cnn.State == ConnectionState.Closed;
            using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
                    if (wasClosed) await ((DbConnection)cnn).OpenAsync().ConfigureAwait(false);
                    using (var reader = await cmd.ExecuteReaderAsync(command.CancellationToken).ConfigureAwait(false))
                        return ExecuteReader(reader, identity, info).ToList();
                    if (wasClosed) cnn.Close();

Should you use asynchronous database calls?

 Just because you can do it does not mean you should do it, says RickAndMSFT at here.


 It does your more harm than good if you queryAsync a small query that takes a few millisecond, however for long running database calls you may consider using querySync feature to avoid bottleneck and gain some responsiveness.

 Check out some benchmark testing from this article Asynchronous Database Calls With Task-based Asynchronous Programming Model (TAP) in ASP.NET MVC 4.

Thursday, July 3, 2014

About 4 years ago, I got a job in a medium-sized company. Before that, I worked in a tiny company. Before that, I worked in a smaller than tiny organization (not for profit). Life in those tinier-to-tiny companies were less hurried, often stagnant.

I would say, life in my current company is fulfilling, at least, very, very, very busy. However, my near-four-year stay at the company has seen (many) people come and go or let go with the fluidity of a free market.

Free market it is.

Sometimes the company let people go in bad times and good times. In bad times, it wanted cut cost so it does not soak in red; In good times, it wanted to "better align company goals and resources" (whatever that means).

A lot of times, people just leave. Why do they leave? There could be bazillions of reasons, for better benefit, better management, better, cooler technologies on the other side of the meadow ... After all, we are not Google, even Google engineers leave.

(An funny anecdote, when I was interviewed, my interviewer enthusiastically told me: We are not Google. Google only want people from, like, Stanford. But we are the next best thing to Google. I was fascinated and held on to that dearly. The next thing to Google sounds just as good as google. Turned out, there is an infinite space between us and google.)

What the impact of people leaving? Especially when the core engineers left.

Culturally ...

I often encounters articles/books about how to be a good programmer, the traits of a good programmer, pragmatic programmers. See here, here, or just here. There all have a grain of truth in it, but I also know, a good programmer is not just born a good one, often, there is a culture that shapes, disciplines,  guides and goads him/her to become one. And the culture is nothing but a bunch of core engineers that hold the same values and principles.

To be honest, good engineers are valuable commodities that are hard to find. To be honest still, we are not google, which makes finding good ones incredibly hard. Hours and hours spent interviewing, sifting through candidates. Weeks and months training a newbie to get know your product,  architecture, coding standards, and the peculiar technologies you are unfortunately heavily dependent upon.

They may or may not become as good as you have hoped. They may excel, be better than you. But they may also leave.


Your productivity will take a huge hit, your performance will suffer. Because instead of the x people working together at an established pace, you are now only one and you have divide your energy into putting-out fire, coding, training people and wondering why people leave and who is next.


Too bad we are not Google. People are leaving, even at a time when the company is prosper, and clients like Google and Yahoo kept jumping in our fish net

Tuesday, July 1, 2014

Let's face it, designing a web template is quite some work, not to mention it takes an eye of aesthetics and the fact that it has to look good on both web and mobile devices. Yes, any web is declaring its own death if it looks crappy on mobile.  So unless you are a professional designer and swimming in loads of money, if you need a quick template, you probably just grab one out there and tweak it and style it to your heart's desire.

That is what I did. And that is why I am so delighted by the various templates at W3 layouts. It has a big collection, and FREE and RESPONSIVE. None of the other template sites come close. (Other popular ones are templates at, but frankly I think they are mostly ugly or perfunctory. WrapBootStrap has some nice ones, but they are not free, though most of them do not cost you most 4 cups of Starbucks.)

Peculiar enough, the templates at W3 layouts often come in three flavors: web, mobile, smart phone. It took me a while to find out that smart phones are for our regular mobile chops: IPhone, android, windows etc. And Mobile templates are designed to use wap 2.0 standards with xhtml where javaScript is not supported. Heck, I guess i can safely discard mobile templates.

Then, the nagging question (quotes from w3

When we have responsive WEB template why we need separate SMARTPHONE and MOBILE template?

Responsive design is good for users having speed network connection (WIFI, 3G). Responsive design will load the whole HTML, CSS and images which are used for desktop design, users in slow data connection have to wait and spend lot of data, time and money to load page. To save users Money and load time we have to use separate design depending on device compatibility.

So I set out to create my little personal site with the fancy and pleasant designs of W3 layouts. Oops, seems that a big part of the world still has not convert to the Microsoft/Asp .net camp, sadly, seems that more and more developers are parting their ways from the gloriously clunky world of Microsoft. (Proof: Why I Left the .NET Framework).

So W3 layouts is in the php camp, and they use a bit of php code to detect user browsers/devices. I would love to use php, but with the time constraint, I am also happy to stick to

So happily and quickly searching (since everything is out somewhere if you search!). I found the following nifty code to get just what I want (got to say it is much more neat and clever than the php code provided by w3 layouts.

C# code (from Mobile Device Detection in

  public static bool IfBrowserIsMobile()
            Debug.Assert(HttpContext.Current != null);

            if (HttpContext.Current.Request != null && HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"] != null)
                var u = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString();

                if(u.Length < 4)
                    return false;

                if (MobileCheck.IsMatch(u) || MobileVersionCheck.IsMatch(u.Substring(0, 4)))
                    return true;

            return false;

The following is the php counterpart:

Saturday, September 7, 2013

Last Friday, we have had a big production release (Yes, instead of incremental daily releases, we still work in a 6-week cycle, adding new features, intenstive QA, then release).

Almost immediately after the release, we had a small trickle of errors discovered. In all, there had been about 6 errors discovered by users or by our product managers. Every time, if I realized that the error was introduced by something I did, my heart sank, my mood went sour, I went into denial, then silently blamed it on QA, then I started fantasizing an error-proof system

Will there ever be one? Even if you planned meticulously, unit tested as much as you can; even if you had UI tests with selenium, JavaScript tests with Jasmine; even if you have QA tested every single feature, then run regression tests on the whole system; even if you tested your web application on all of the browsers, IE 9 &10, Chrome, Firefox ... errors still unexpected creep in.

If it is ever possible to eliminate bugs? And how much tests are enough?

Maybe bugs in code are as common and inevitable as flaws in human beings.