Tuesday, 10 December 2013

Using different methods of casting in C++

In C++ there are several types of casting that you can use.

static_cast

static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:
 
void func(void *data) {
  // conversion from MyClass* -> void* is implicit
  MyClass *c = static_cast<MyClass*>(data);
  ...
}

int main() {
  MyClass c;
  start_thread(&func, &c)  // func(&c) will be called
      .join();
}
In this example, you know that you passed a MyClass object, and thus there is no need for a runtime check to ensure this.

dynamic_cast

dynamic_cast is used for cases where you don't know what the dynamic type of the object is. You cannot use dynamic_cast if you downcast and the argument type is not polymorphic. An example that checks the object type before performing an operation.

if(JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
  ...
} else if(ExprStm *e = dynamic_cast<ExprStm*>(&stm)) { 
  ...
}
 
dynamic_cast returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case).
The following code is not valid, because Base is not polymorphic (doesn't contain a virtual function):

struct Base { };
struct Derived : Base { };
int main() { 
  Derived d;  
  Base *b = &d;
  dynamic_cast<Derived*>(b); // invalid
}
An "up-cast" is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion.

Regular Cast

These casts are also called c-style cast. A c-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first c++ cast that works, without ever considering dynamic_cast. Needless to say that this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe because it does not use dynamic_cast.
In addition, C-style casts not only allow you to do this, but also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile time error for that.
Some people prefer c-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.

reinterpret_cast

reinterpret_cast is necessary is when interfacing with opaque data types. This occurs frequently in vendor APIs over which the programmer has no control. Here's a contrived example where a vendor provides an API for storing and retrieving arbitrary global data:

// vendor.hpp
typedef struct _Opaque * VendorGlobalUserData;
void VendorSetUserData( VendorGlobalUserData p );
VendorGlobalUserData VendorGetUserData();
 
To use this API, the programmer must cast their data to VendorGlobalUserData and back again.  

static_cast won't work, one must use reinterpret_cast:

// main.cpp
#include "vendor.hpp"
#include <iostream>
using namespace std;

struct MyUserData {
    MyUserData() : m( 42 ) {}
    int m;
};

int main() {
    MyUserData u;

    // store global data
    VendorGlobalUserData d1;
 
//  d1 = &u;                                             // compile error
 
//  d1 = static_cast< VendorGlobalUserData >( &u );      // compile error
 
    d1 = reinterpret_cast< VendorGlobalUserData >( &u ); // ok
 
    VendorSetUserData( d1 );

    // do other stuff...

    // retrieve global data 
    VendorGlobalUserData d2 = VendorGetUserData();
    MyUserData * p = 0;
 
//  p = d2;                                              // compile error 
 
//  p = static_cast< MyUserData * >( d2 );               // compile error 
 
    p = reinterpret_cast< MyUserData * >( d2 );          // ok

    if ( p ) { cout << p->m << endl; }
    return 0;
}
 
Below is a contrived implementation of the sample API:

// vendor.cpp
static VendorGlobalUserData g = 0;
void VendorSetUserData( VendorGlobalUserData p ) { g = p; }
VendorGlobalUserData VendorGetUserData() { return g; }

Monday, 9 December 2013

Code reuse and inheritance in JavaScript.



JavaScript can be used like a classical language, but it also has a level of expressiveness which is quite unique. The types of inheritance that can be used are Classical Inheritance, Swiss Inheritance, Parasitic Inheritance, Class Augmentation, and Object Augmentation. This large set of code reuse patterns comes from a language which is considered smaller and simpler than Java.

http://www.crockford.com/javascript/inheritance.html

JavaScript is a class-free, object-oriented language, and as such, it uses prototypal inheritance instead of classical inheritance. This can be puzzling to programmers trained in conventional object-oriented languages like C++ and Java. JavaScript's prototypal inheritance has more expressive power than classical inheritance, as we will see presently. But first, why do we care about inheritance at all? There are primarily two reasons. The first is type convenience. We want the language system to automatically cast references of similar classes. Little type-safety is obtained from a type system which requires the routine explicit casting of object references. This is of critical importance in strongly-typed languages, but it is irrelevant in loosely-typed languages like JavaScript, where object references never need casting.
The second reason is code reuse. It is very common to have a quantity of objects all implementing exactly the same methods. Classes make it possible to create them all from a single set of definitions. It is also common to have objects that are similar to some other objects, but differing only in the addition or modification of a small number of methods. Classical inheritance is useful for this but prototypal inheritance is even more useful.
To demonstrate this, we will introduce a little sugar which will let us write in a style that resembles a conventional classical language. We will then show useful patterns which are not available in classical languages. Then finally, we will explain the sugar.

Classical Inheritance

First, we will make a Parenizor class that will have set and get methods for its value, and a toString method that will wrap the value in parens.
function Parenizor(value) {
    this.setValue(value);
}

Parenizor.method('setValue', function (value) {
    this.value = value;
    return this;
});

Parenizor.method('getValue', function () {
    return this.value;
});

Parenizor.method('toString', function () {
    return '(' + this.getValue() + ')';
});
The syntax is a little unusual, but it is easy to recognize the classical pattern in it. The method method takes a method name and a function, adding them to the class as a public method.
So now we can write
myParenizor = new Parenizor(0);
myString = myParenizor.toString();
As you would expect, myString is "(0)".
Now we will make another class which will inherit from Parenizor, which is the same except that its toString method will produce "-0-" if the value is zero or empty.
function ZParenizor(value) {
    this.setValue(value);
}

ZParenizor.inherits(Parenizor);

ZParenizor.method('toString', function () {
    if (this.getValue()) {
        return this.uber('toString');
    }
    return "-0-";
});
The inherits method is similar to Java's extends. The uber method is similar to Java's super. It lets a method call a method of the parent class. (The names have been changed to avoid reserved word restrictions.)
So now we can write
myZParenizor = new ZParenizor(0);
myString = myZParenizor.toString();
This time, myString is "-0-".
JavaScript does not have classes, but we can program as though it does.

Multiple Inheritance

By manipulating a function's prototype object, we can implement multiple inheritance, allowing us to make a class built from the methods of multiple classes. Promiscuous multiple inheritance can be difficult to implement and can potentially suffer from method name collisions. We could implement promiscuous multiple inheritance in JavaScript, but for this example we will use a more disciplined form called Swiss Inheritance.
Suppose there is a NumberValue class that has a setValue method that checks that the value is a number in a certain range, throwing an exception if necessary. We only want its setValue and setRange methods for our ZParenizor. We certainly don't want its toString method. So, we write
ZParenizor.swiss(NumberValue, 'setValue', 'setRange');
This adds only the requested methods to our class.

Parasitic Inheritance

There is another way to write ZParenizor. Instead of inheriting from Parenizor, we write a constructor that calls the Parenizor constructor, passing off the result as its own. And instead of adding public methods, the constructor adds privileged methods.
function ZParenizor2(value) {
    var that = new Parenizor(value);
    that.toString = function () {
        if (this.getValue()) {
            return this.uber('toString');
        }
        return "-0-"
    };
    return that;
}
Classical inheritance is about the is-a relationship, and parasitic inheritance is about the was-a-but-now's-a relationship. The constructor has a larger role in the construction of the object. Notice that the uber née super method is still available to the privileged methods.

Class Augmentation

JavaScript's dynamism allows us to add or replace methods of an existing class. We can call the method method at any time, and all present and future instances of the class will have that method. We can literally extend a class at any time. Inheritance works retroactively. We call this Class Augmentation to avoid confusion with Java's extends, which means something else.

Object Augmentation

In the static object-oriented languages, if you want an object which is slightly different than another object, you need to define a new class. In JavaScript, you can add methods to individual objects without the need for additional classes. This has enormous power because you can write far fewer classes and the classes you do write can be much simpler. Recall that JavaScript objects are like hashtables. You can add new values at any time. If the value is a function, then it becomes a method.
So in the example above, I didn't need a ZParenizor class at all. I could have simply modified my instance.
myParenizor = new Parenizor(0);
myParenizor.toString = function () {
    if (this.getValue()) {
        return this.uber('toString');
    }
    return "-0-";
};
myString = myParenizor.toString();
We added a toString method to our myParenizor instance without using any form of inheritance. We can evolve individual instances because the language is class-free.

Sugar

To make the examples above work, I wrote four sugar methods. First, the method method, which adds an instance method to a class.
Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};
This adds a public method to the Function.prototype, so all functions get it by Class Augmentation. It takes a name and a function, and adds them to a function's prototype object.
It returns this. When I write a method that doesn't need to return a value, I usually have it return this. It allows for a cascade-style of programming.
Next comes the inherits method, which indicates that one class inherits from another. It should be called after both classes are defined, but before the inheriting class's methods are added.
Function.method('inherits', function (parent) {
    this.prototype = new parent();
    var d = {}, 
        p = this.prototype;
    this.prototype.constructor = parent; 
    this.method('uber', function uber(name) {
        if (!(name in d)) {
            d[name] = 0;
        }        
        var f, r, t = d[name], v = parent.prototype;
        if (t) {
            while (t) {
                v = v.constructor.prototype;
                t -= 1;
            }
            f = v[name];
        } else {
            f = p[name];
            if (f == this[name]) {
                f = v[name];
            }
        }
        d[name] += 1;
        r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
        d[name] -= 1;
        return r;
    });
    return this;
});
Again, we augment Function. We make an instance of the parent class and use it as the new prototype. We also correct the constructor field, and we add the uber method to the prototype as well.
The uber method looks for the named method in its own prototype. This is the function to invoke in the case of Parasitic Inheritance or Object Augmentation. If we are doing Classical Inheritance, then we need to find the function in the parent's prototype. The return statement uses the function's apply method to invoke the function, explicitly setting this and passing an array of parameters. The parameters (if any) are obtained from the arguments array. Unfortunately, the arguments array is not a true array, so we have to use apply again to invoke the array slice method.
Finally, the swiss method.
Function.method('swiss', function (parent) {
    for (var i = 1; i < arguments.length; i += 1) {
        var name = arguments[i];
        this.prototype[name] = parent.prototype[name];
    }
    return this;
});
The swiss method loops through the arguments. For each name, it copies a member from the parent's prototype to the new class's prototype.

Sunday, 8 December 2013

How to handle JQuery AJAX calls without resorting to SJAX


The A in AJAX stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.
Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer:

Synchronous

Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer you needed.
The same is happening when you make a function call containing "normal" code:

function findItem() {
    var item;
    while(item_not_found) {
        // search
    }
    return item;
}

var item = findItem();
// do something with item
doSomethingElse();
Even though findItem might take a long time to execute, any code coming after var item = findItem(); has to wait until the function returns the result.

Asynchronous

You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.
That's exactly what's happening when you do an AJAX request.

findItem(function(item) {
    // do something with item
});
doSomethingElse();
 
Instead of waiting for the response, the execution continues immediately and the statement after the AJAX call is executed. To get the response eventually, you provide a function to be called once the response was received, a callback (notice something? call back ?). Any statement coming after that call is executed before the callback is called.

Solutions

There are basically two ways how to solve this:
  1. Make the AJAX call synchronous (lets call it SJAX).
  2. Restructure your code to work properly with callbacks.

1. Synchronous AJAX calls -- DON'T DO IT

It is generally a bad idea to make AJAX calls synchronous. DON'T DO IT. I'm serious. I only mention it here for the sake of completeness. Why is it bad do you ask?
JavaScript runs in the UI thread of the browser and any long running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not. All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore the effect will be worse for users with a slow connection.

jQuery

If you use jQuery, you can set the async option to false. Note that this option is deprecated since jQuery 1.8. You can then either still use a success callback or access the responseText property of the jqXHR object:

function foo() {
    var jqXHR = $.ajax({
        //...
        async: false
    });
    return jqXHR.responseText;
}
 
If you use any other jQuery AJAX method, such as $.get, $.getJSON, etc., you have to change it to $.ajax (since you can only pass configuration parameters to $.ajax).
Heads up! It is not possible to make a synchronous JSONP request. JSONP by its very nature is always asynchronous (one more reason to not even consider this option).

Without jQuery

If you directly use a XMLHTTPRequest object, pass false as second argument to .open.

2. Restructure code

Let functions accept callbacks

The better approach is to organize your code properly around callbacks. In the example in the question, you can make foo accept a callback and use it as success callback. So this
var result = foo();
// code that depends on 'result'
becomes
foo(function(result) {
    // code that depends on 'result'
});
Here we pass a function as argument to foo. You can pass any function reference, for example:
function myCallback(result) {
    // code that depends on 'result'
}

foo(myCallback);
foo itself is defined as follows:
function foo(callback) {
    $.ajax({
        // ...
        success: callback
    });
}
callback will refer to the function we pass to foo when we call it and we simply pass it on to success. I.e. once the AJAX request is successful, $.ajax will call callback and pass the response to the callback (which can be referred to with result, since this is how we defined the callback).
You can also process the response before passing it to the callback:
function foo(callback) {
    $.ajax({
        // ...
        success: function(response) {
            // e.g. filter the response
            callback(filtered_response);
        }
    });
}
It's easier to write code using callbacks than it seems. After all, JavaScript in the browser is heavily event driven (DOM events). Receiving the AJAX response is nothing else but an event.
Difficulties could arise when you have to work with third party code, but most problems can be solved by just thinking through the application flow.

Use deferred objects / promises

While directly passing callbacks works just fine, it can become inflexible in certain situations. Deferred objects / promises are a great way to deal with many callbacks and decouple your code.
Deferred objects are not unique to jQuery (see also the Promise/A proposal) and there many independent implementations but I will only focus on jQuery in this answer.
Luckily for us, every AJAX method of jQuery already returns a promise which you can just return from your function and the calling code decides how to attach the callbacks:
function foo() {
    return $.ajax(...);
}

foo().done(function(result) {
    // code depending on result
}).fail(function() {
    // an error occurred
});
Describing all the advantages that deferred objects offer is beyond the scope of this answer, but if you write new code, you should seriously consider them. They provide a great abstraction and separation of your code.

Improving Bad Code

Deferreds can make it easy to transform broken asynchronous code into working code. For example suppose you had the following:
function checkPassword() {
    return $.ajax({
        url: '/password',
        data: {
            username: $('#username').val()
            password: $('#password').val()
        },
        type: 'POST',
        dataType: 'json'
    });
}

if (checkPassword()) {
    // Tell the user they're logged in
}
This code misunderstands the above asynchrony issues. Specifically, $.ajax() doesn't freeze the code while it checks the '/password' page on your server - it sends a request to the server and while it waits, immediately returns a jQuery Ajax Deferred object, which means your if statement is going to always get this Deferred object, treat that as true, and proceed as though the user is logged in. Not good.
But the fix is easy:
checkPassword()
.done(function(r) {
    if (r) {
        // Tell the user they're logged in
    } else {
        // Tell the user their password was bad
    }
})
.fail(function(x) {
    // Tell the user something bad happened
});
So now we're still calling the '/password' page on the server, but our code now properly handles the wait time for the server to respond. The $.ajax() call still returns immediately with a jQuery Ajax Deferred object, but we use it to attach event listeners to .done() and .fail(). In the .done() call, where the server responded with a normal response (HTTP 200), we check the object returned by the server. In this example the server is just returning true if the login was successful, false if not, so if (r) is checking for true/false.
In the .fail() handler we're dealing with something going wrong - for example if the user lost their internet connection while they were typing in their username and password, or if your server went down.