Five Lessons From JavaScript: The Good Parts

Ronnie Mukherjee 0 Comments

js_good_parts

I have just finished reading JavaScript: The Good Parts by Douglas Crockford. It is a quite illuminating book, from which I learnt a number of interesting and useful lessons about JavaScript. I have chosen five to share with you below. If you are interested in JavaScript, you might find something useful here and I would strongly encourage you to buy and read the book yourself.

undefined and null

If I had been asked what the simple types in JavaScript were before reading this book, I would have replied with number, string and boolean. In fact there are two more simple types in JavaScript: null, and undefined. Having worked with JavaScript for many years, I have of course encountered null and undefined many times, but had never really considered their types, or that they are indeed simple types themselves.

So what is the difference between undefined and null?

When you try to retrieve the value of a property or variable which has either not been assigned a value, or which has not been declared, you will receive the undefined value.

The null value must be explicitly assigned to a property or variable before it is encountered.

However, matters are complicated by the fact that the expression (null == undefined) returns true, which means that in the following code, our alert is raised.

1
2
3
4
5
var notAssigned; // will return undefined
 
if(notAssigned == null){
  alert(‘it is null!);
}
var notAssigned; // will return undefined

if(notAssigned == null){
  alert(‘it is null!’);
}

…which brings us to the two sets of equality operators.

== and ===

For programmers like myself who come from an object-oriented language background, it is easy to fall into the trap of making a lot of assumptions about the JavaScript syntax without really taking the time to check those assumptions.

An easy mistake to make is to assume that the “double equals” equality operator == has the same basic meaning as in JavaScript as it does in C#. However, there is an important difference.

In C#, the double equals will only return true if the two operands either point to the same reference (for reference types) or contain identical values (for value types). In JavaScript, the double equals can return true even if the two operands are of different types. The reason for this is that when the double equals is presented with operands of different types, it will attempt to convert one of the operands to the type of the other, and compare the result. Below are examples taken directly from the book, which demonstrate some of the strange consequences of this behaviour.

1
2
3
4
5
6
7
8
9
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true

The other equality operator offered by JavaScript is the triple equals, ===. This displays behaviour which is more like what we would expect. It does not attempt to do any conversions when presented with operands of different types, it just returns false. So in each of the examples listed above, false would be returned.

The double equals operator is identified by Crockford as one of the bad parts of JavaScript, and he advises against using it under any circumstances.

Objects are Containers of Properties

Having confirmed that all values in JavaScript are either simple types or objects, an “aha” moment for me was reading that all objects in JavaScript are simply containers of properties. It’s a satisfying feeling being able to abstract a seemingly complex or unclear concept into a simple model (isn’t this in fact the whole purpose of science?). From my experience with JSON and object literals, I was quite familiar with the concept of properties and values in JavaScript. However it had never dawned on me that objects are simply containers of properties, with each property consisting of a name and a value. That value can of course be another object, which contains its own properties, and so on. Objects in C# are more complicated . A C# object can have a variety of different types of members, including methods, events, delegates and properties. Furthermore, each of these members is associated with a visibility level, such as ‘public’ or ‘private’. Behaviour according to differing levels of visibility can be emulated in JavaScript, as I discussed in a previous post, however this feature is not built in to the language. I find the fact that objects are such simple constructs an almost beautiful feature of JavaScript.

Another important feature of objects is the prototype linkage feature, but that is probably a topic for a separate blog post.

Functions are Objects

Functions in JavaScript are themselves objects, which means, as we have seen, that they are simply containers of properties. How is a function simply a container of properties? In a nutshell it has hidden properties for the function’s context and its enclosed statements. The important difference between a function and any other object is that a function can be invoked.

The fact that functions are objects means that they can be assigned to a variable, stored in an array, passed as an argument to a different function, or used in any other way that a ‘regular’ object might be used.

An interesting aspect of functions in JavaScript is the value of this inside of a function, which I discussed in a previous post.

Function Scope in JavaScript

This is something I feel I really should have known about JavaScript, but I must confess I didn’t.

Variables in JavaScript have function scope, unlike C# which has block scope. What this means is that when you declare a variable in JavaScript, it is accessible by any code within the same function, even if that code exists outside of your current block, as defined by your curly braces. This is probably best explained by an example:

1
2
3
4
5
6
7
8
var myFunction = function()
{
  if(10 > 5)
  {
    var message = ‘hello there!;
  }
  alert(message); // alerts 'hello there!'
}
var myFunction = function()
{
  if(10 > 5)
  {
    var message = ‘hello there!’;
  }
  alert(message); // alerts 'hello there!'
}

If JavaScript had block scope, like C# and Java do, then invoking myFunction would cause undefined to be alerted. In fact our message ‘hello there!’ is alerted.

For reasons of clarity Crockford advises us to always declare our variables at the top of the containing function. So our code would then look like this:

1
2
3
4
5
6
7
8
9
10
11
var myFunction = function()
{
  var message;
 
  if(10 > 5)
  {
    message = ‘hello there!;
  }
 
  alert(message);
}
var myFunction = function()
{
  var message;

  if(10 > 5)
  {
    message = ‘hello there!’;
  }

  alert(message);
}

Having function scope rather than block scope is identified by Crockford as one of the ‘awful’ parts of JavaScript.

Final Words

In summary, this is a book that is well worth reading for anyone interested in the finer points of JavaScript. My next goal in developing knowledge and understanding in my chosen niche is to start looking at angular in more detail. I’m not yet sure how I will go about this, but the free tutorial over at codeschool.com looks like it could be a great place to start.

Is Contracting For You?

Ronnie Mukherjee 2 Comments

contract

I  have been contracting for around two and a half years now. This isn’t long at all in the grand scheme of things, nevertheless I thought I would share some thoughts on contracting compared with permanent employment, from my slightly limited point of view. If you are considering taking the plunge into the world of contracting, you may find this useful.

Being an Outsider

Becoming a contractor requires a slight psychological adjustment. As a permanent member of staff you become used to playing by the same rules as your colleagues. Everyone adheres to the same policies and principles, from working hours and holiday allowance to pension schemes, performance appraisals and career development plans. This leads to a subtle sense of belonging to a team, which needs to be recognised and compensated for by contractors. I am of course a part of my client’s team and I work hard to achieve success in my projects, but there is no denying that in some respects I will always be an outsider compared to permanent staff. It took me some time to get used to this.

Lack of Security

I have been fortunate enough to have never been short of work since becoming a contractor. However, by the very nature of contracting it is necessary to always keep one eye on your next job. When times are hard in industry, contractors are often the first to go, and it is important to never take one’s position for granted. It is true that anyone can be made redundant, however contractors obviously change their place of work more frequently, and this means more job hunting, more interviews, and potentially more stress. The idea of being out of work is frightening for anyone. We all have responsibilities to meet and bills to pay.  For contractors this fear is likely to rear its head more often than for permanent employees.

More Paperwork

If you set yourself up as a limited company, as most contractors do, there will be some additional paperwork for you to do to manage your business finances and payment of taxes. If you hire an accountancy this will help, however you will still have at least a little admin work to do each month, and accountants obviously charge you for their time.

Expectations

As a contractor you will be expected to have a certain degree of technical expertise. You will be expected to hit the ground running. Your employers will not hire you based on potential or willingness to learn, you will be expected to have already fulfilled much potential and learnt a great deal. This can be daunting, but equally it can motivate you to actually spend some time and effort on developing and maintaining your skills, and thus speed up your development. Since becoming a contractor I have spent more of my personal time learning than I ever did when I was a regular employee.

Getting a Mortgage

One aspect of contracting I had not considered was the added complications when applying for a mortgage. I have recently moved house and my first mortgage application was rejected because I did not have two full years of accounts to show the bank. Thankfully another bank was more flexible. If you are thinking of applying for a mortgage in the next two to three years then now may not be the best time for you to become a contractor. At the very least do some research. Any other application which requires proof of a steady income may be subject to similar complications.

More Money

This is perhaps the biggest draw to the world of contracting. It is no secret that contractors are paid more for their time than permanent members of staff. It is easy to overestimate the difference however. We still need to pay taxes and we do not receive any paid holidays, pension contributions, company car or other benefits. Furthermore, there will probably be times in between contracts when we are looking for work and obviously not being paid at all. That said, my earnings through contracting are higher than they would be if I were a permanent employee. If you can repeatedly find work, then you will likely receive more money as a contractor, but you must be confident in your ability to find that work.

Varied Experience

As valuable as book-reading and personal projects are, in my opinion there is no substitute for commercial experience when it comes to your professional development. As a contractor you will experience a great deal of variety with regards to projects, people, working environments and working practices. This will allow you to better understand what actually matters and what doesn’t when it comes to achieving commercial success. You will probably work with a variety of different tools, on projects of different lengths, and will have to communicate with different types of colleagues and customers. You are less likely to get bored and as scary as it can be not knowing where your next job will come from, the anticipation of a new challenge can be exciting.

Freedom From Office Politics

Successful organisations are of course made up of people who want to get ahead. Naturally everyone is aiming for that big promotion and pay rise. This is just human nature and there is certainly nothing fundamentally wrong with it. One consequence of this however can be a high level of unhealthy competitiveness in the workplace. Sometimes employees can be so eager to impress the boss that they will engage in questionable behaviour. This might be taking credit for someone else’s work, failing to accept responsibility for mistakes made or even worse, blaming someone else. As a contractor there is no guarantee of freedom from such political games, but as you are outside of the race for promotion, you are less likely to become embroiled in them.

Autonomy

Permanent employees are often guided towards learning about particular technologies or programming languages, according to the needs of the business. Contractors on the other hand have a greater degree of control over their professional development path. We can assess the market and find a compromise between which skills are in demand, and which areas we are interested in learning about. This freedom to be your own career development manager can be quite liberating.

Final Thoughts

If you are thinking of becoming a contractor then I hope my thoughts have helped you. It is not for everyone. There are certainly advantages to permanent employment, and the right decision will depend upon your individual circumstances, including your financial responsibilities, your skill set, and your geographical location. I took all these things into account when I made my decision, and I certainly have no regrets, but I would encourage anyone to look very carefully before you leap.

Life Without Resharper

Ronnie Mukherjee 0 Comments

I recently (finally) upgraded to visual studio 2013. One unfortunate consequence of this was that the version of Resharper I was using (v7) was no longer supported. I was disappointed to find that my license was not enough to obtain a free upgrade, therefore I was faced with a choice: either buy a license for Resharper 8, or try programming without Resharper in the hope that VS2013 would offer enough features to allow me to achieve similar levels of productivity and flow. There is a certain appeal to the idea of learning to code without Resharper. We all know dependencies should be minimized.

So I decided to try life without Resharper.

I lasted 3 days.

Admittedly VS2013 does offer adequate or even superior equivalents for many of Resharper’s features. For example, I actually prefer Visual Studio’s unit test runner to Resharper’s. It seems to run faster and is more reliable. Extracting a method is also fine using Visual Studio alone. However there are a number of features which make programming with Resharper not only faster, but more satisfying.

The Alt-Enter Panacea

The Alt-Enter cure-all keyboard shortcut offered by Resharper is genius. The official name for this command is ‘show action list’, but the brilliant thing about it is its sensitivity to your current context. Resharper knows what actions you may want to perform given the position of your cursor. You might want to rename a variable to adhere to coding standards, rename a file to match the name of a class, generate a method stub for some calling code you’ve just written, remove an unused variable, remove unused using statements… the list goes on. There is no equivalent context-specific intelligence in Visual Studio. The best we can do is to learn the keyboard shortcut for each useful action, but there are several actions offered by Resharper’s Alt-Enter command that appear to have no equivalent in VS2013. For example, the only way I can see to locate and report on unused variables without Resharper is through Visual Studio’s static code analysis feature. This can either be run manually on demand, or each time you build your project. You are then required to manually remove each occurrence of dead code that is reported. Compare this to Resharper which greys out dead code as you write it, and lets you quickly and automatically remove it using Alt-Enter. The same can be said about many of Resharper’s best features. Resharper’s analysis is dynamic, whereas Visual Studio’s is static. The significance of this difference shoulod not be underestimated. With dynamic analysis it is far easier to gain and maintain momentum as you code.

Go To Implementation

In trying to code without Resharper, it wasn’t long before I needed a way to go directly to the implementation of a method, from calling code which referenced an interface. No problem, I thought, I’ll just look up the keyboard shortcut. After a little Googling, I was amazed to find that Visual Studio has no ‘Go To Implementation’ shortcut. I still can’t believe this. We live in a world where we are told (quite rightly) to favour dependency injection in the form of interfaces. Therefore a huge portion of our calling code will call methods defined on interfaces. The value of the ‘Go To Definition’ command is obvious: we want to look at the code contained within a called method. Thus, the ‘Go To Implementation’ command is just as valuable. Yet Visual Studio does not have it. The closest equivalent I could find was a 3-step process described in this stackoverflow discussion. A 3 step process! This is simply not good enough and is one of the key reasons that I decided to go back to Resharper.

Business idea or invention icon -  brain with gear wheel and light bulb

Conclusions

When I decided to try coding without Resharper I was fairly confident I would be fine. I thought it would just be a case of learning some Visual Studio keyboard shortcuts. But in terms of helping programmers to produce good quality code more quickly, Resharper is streets ahead of VS2013. Its dynamic code analysis is almost like pair programming with an observant and capable partner, who will tell you how to keep your code clean and tidy as you write it, and step in to perform uninteresting and repeatable tasks such as removing dead code and generating methods. I wouldn’t say Resharper is cheap, but there is just no cheaper alternative. CodeRush by DevExpress is apparently a good product but it also isn’t cheap. I believe we do our best work and gain the most satisfaction when we can enter a state of flow when coding. Our brains work a lot quicker than our hands, and we need to be able to express an idea as quickly as possible, to allow us to move on to our next idea. To anyone who spends a lot of time coding in Visual Studio without Resharper, I would urge you to download the free trial and give it a try. If you can get used to it in 30 days, you will probably never go back.

Information Hiding in JavaScript

Ronnie Mukherjee 2 Comments

info hiding

A key concept in object-oriented programming is information hiding. It refers to the practice of declaring some parts of a class public, and others private, depending on what we want clients of the class to be able to see and do. It protects the application from programmers who may decide to use a class in ways which are contrary to the original intentions of the class’s author.

Unlike object-oriented languages such as Java and C#, the JavaScript syntax does not include keywords such as ‘public’ and ‘private’ (access modifiers) which would allow programmers to practice information hiding quickly and easily. However many programmers, myself included, are used to designing applications based on object-oriented programming, so we need a way to simulate this concept using the features available in the JavaScript language.

There are essentially two ways to do this: using constructor functions, and using the module pattern.

Constructor Functions

I touched on constructor functions in my last post. These are basically functions which are intended to be called with the ‘new’ keyword. By calling a function in this way, we create an object based on the function, with its own state, and where any occurrence of the ‘this’ prefix inside the function will create a public property or function on the created object.

This feature of JavaScript was added to appeal to programmers coming from an object-oriented background, where the ‘new’ keyword is a fundamental feature.

Notice in the example below how the name of the function is capitalized – this is conventional when declaring constructor functions to remind us to treat it as such and to call it with the ‘new’ keyword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function Rectangle() // capitalized name convention
{
    // private stuff
    var height;
    var width;
    
    // public stuff
    this.getArea = function(){
        return height*width;
    };
    
    this.setWidth = function(w){
        width = w;
    };
    
    this.setHeight = function(h){
        height = h;
    };
    
    this.shapeType = 'rectangle';
}
 
var rect = new Rectangle(); // use new keyword
rect.setWidth(4);
rect.setHeight(3);
alert(rect.getArea()); // alerts 12
alert(rect.shapeType); // alerts 'rectangle'
alert(rect.height); // alerts 'undefined'
 
var rect2 = new Rectangle();
rect2.setWidth(10);
rect2.setHeight(2);
alert(rect2.getArea()); // alerts 20
alert(rect2.shapeType); // alerts 'rectangle'
alert(rect2.height); // alerts 'undefined'
function Rectangle() // capitalized name convention
{
    // private stuff
    var height;
    var width;
    
    // public stuff
    this.getArea = function(){
        return height*width;
    };
    
    this.setWidth = function(w){
        width = w;
    };
    
    this.setHeight = function(h){
        height = h;
    };
    
    this.shapeType = 'rectangle';
}

var rect = new Rectangle(); // use new keyword
rect.setWidth(4);
rect.setHeight(3);
alert(rect.getArea()); // alerts 12
alert(rect.shapeType); // alerts 'rectangle'
alert(rect.height); // alerts 'undefined'

var rect2 = new Rectangle();
rect2.setWidth(10);
rect2.setHeight(2);
alert(rect2.getArea()); // alerts 20
alert(rect2.shapeType); // alerts 'rectangle'
alert(rect2.height); // alerts 'undefined'

Constructor functions also allow us to modify all instances, including ones which have already been created, by updating the function’s prototype property, as shown below.

1
2
3
var rect = new Rectangle();
Rectangle.prototype.numberOfCorners = 4;
alert(rect.numberOfCorners); // alerts '4'
var rect = new Rectangle();
Rectangle.prototype.numberOfCorners = 4;
alert(rect.numberOfCorners); // alerts '4'

The Module Pattern

The module pattern essentially describes the practice of writing a function which returns an object literal. The function represents our object-oriented class. Any client of this ‘class’ has access only to the object literal returned by the function. Therefore, members defined as part of this object literal are effectively public. Any members declared inside of the function are private, however, they are accessible from the object literal thanks to the concept of closures in JavaScript.

We can see how this works in code in this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function getRectangleInstance()
{
    // private stuff
    var height;
    var width;
    
    // public stuff on returned object
    return {
        getArea: function(){
            return height*width;
        },
        setWidth: function(w){
            width = w;
        },
        setHeight: function(h){
            height = h;
        },
        shapeType: 'rectangle'
    };
}
 
var rect = getRectangleInstance();
rect.setWidth(4);
rect.setHeight(3);
alert(rect.getArea()); // alerts 12
alert(rect.shapeType); // alerts 'rectangle'
alert(rect.height); // alerts 'undefined'
 
var rect2 = getRectangleInstance();
rect2.setWidth(10);
rect2.setHeight(2);
alert(rect2.getArea()); // alerts 20
alert(rect2.shapeType); // alerts 'rectangle'
alert(rect2.height); // alerts 'undefined'
function getRectangleInstance()
{
    // private stuff
    var height;
    var width;
    
    // public stuff on returned object
    return {
        getArea: function(){
            return height*width;
        },
        setWidth: function(w){
            width = w;
        },
        setHeight: function(h){
            height = h;
        },
        shapeType: 'rectangle'
    };
}

var rect = getRectangleInstance();
rect.setWidth(4);
rect.setHeight(3);
alert(rect.getArea()); // alerts 12
alert(rect.shapeType); // alerts 'rectangle'
alert(rect.height); // alerts 'undefined'

var rect2 = getRectangleInstance();
rect2.setWidth(10);
rect2.setHeight(2);
alert(rect2.getArea()); // alerts 20
alert(rect2.shapeType); // alerts 'rectangle'
alert(rect2.height); // alerts 'undefined'

This variation of the module pattern (there are many), allows us to easily create multiple instances of a class, each of which has its own state.

Which One to Use?

The question of whether to use constructor functions or the module pattern to enforce information hiding in JavaScript is largely a personal choice. In JavaScript – The Good Parts, Douglas Crockford seems to identify constructor functions as a ‘bad part’ of JavaScript, his reasoning being that forgetting to use the ‘new’ keyword when calling a constructor function can lead to unexpected behaviour. However, constructor functions do allow us to easily modify all instances of a class by modifying the function’s prototype property.

Personally I don’t really see a problem with using constructor functions. Or rather, I don’t see the possibility of forgetting to use ‘new’ as enough of a reason to avoid using them. Just try not to forget! Constructor functions are a powerful feature and they arguably make for more readable code, particularly to those coming from an object-oriented background, not to mention the added advantage of emulating inheritance by accessing the function’s prototype.

As the name suggests, I see the module pattern as being more useful to emulate modules, rather than classes which act as templates for multiple instances. By using the module pattern to define an immediately invoked function expression, we can create a module which is not intended to be instantiated multiple times, but which encapsulates a set of functionality and avoids littering the global namespace. In the example below we implement the module pattern in this way, declaring an immediately invoked function to assign an object to the shapeModule variable. This object, or module, can contain its own private members, and exposes the getRectangleInstance function, along with any other desired public members. However, by immediately invoking the shapeModule function, we lose the ability to create multiple instances of it. Therefore this variation of the module pattern is often described as emulating the concept of a namespace, rather than a class, in Java or C#.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var shapeModule = function(){
    
    // stuff private to the shape module
    var privateField = 'someValue';
    
    return {
        getRectangleInstance: function(){
            // stuff private to the rectangle instance
            var height;
            var width;
                
            return {
                getArea: function(){
                    return height*width;
                },
                setWidth: function(w){
                    width = w;
                },
                setHeight: function(h){
                    height = h;
                },
                shapeType: 'rectangle'
            };            
        },
        getCircleInstance: function(){
            // code for circles
        }
    };        
}(); // function is immediately invoked
 
var rect = shapeModule.getRectangleInstance();
alert(rect.shapeType); // alerts 'rectangle'
var shapeModule = function(){
    
    // stuff private to the shape module
    var privateField = 'someValue';
    
    return {
        getRectangleInstance: function(){
            // stuff private to the rectangle instance
            var height;
            var width;
                
            return {
                getArea: function(){
                    return height*width;
                },
                setWidth: function(w){
                    width = w;
                },
                setHeight: function(h){
                    height = h;
                },
                shapeType: 'rectangle'
            };            
        },
        getCircleInstance: function(){
            // code for circles
        }
    };        
}(); // function is immediately invoked

var rect = shapeModule.getRectangleInstance();
alert(rect.shapeType); // alerts 'rectangle'

The important message here is that it is possible, and desirable, to implement information hiding in JavaScript, and once you know how it is not too difficult to do so.

Something Like “this”

Ronnie Mukherjee 3 Comments

Few people learn JavaScript as a first programming language. Typically people will start with an object-oriented language such as C#, Java or C++. These languages have a few things in common, such as curly braces, objects, functions, if-statements and loops. Another common feature of object-oriented programming languages is the ‘this’ keyword. It refers to the class which contains the currently executing code.

It can be something of a surprise then when a programmer moves on to JavaScript and discovers that the value returned by ‘this’ is less predictable than expected.

There are five different cases where you might use ‘this’. These include using it in the global namespace, and four different ways of using it inside a function, as described by Douglas Crockford in JavaScript – The Good Parts.

‘this’ in the Global Namespace

In the global namespace, that is, outside of any function, ‘this’ refers to the window object. I don’t see any reason why anyone would want to use ‘this’ in the global namespace, in fact it’s probably a bad idea, nevertheless it can be done and so is worth mentioning for completeness.

Scenario 1 – Method Invocation

In JavaScript (and many other languages) a method is a function which is declared inside of a class or object. Referring to ‘this’ inside of a method refers to the containing object. Therefore in the example below we are alerted with ‘Roberto Martinez’ rather than ‘Howard Kendall’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Set global variable
var manager = 'Howard Kendall';
 
// 1. Method Invocation
var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {
            return this.manager;
        }
    };
 
alert(everton.getManager()); // alerts 'Roberto Martinez'
// Set global variable
var manager = 'Howard Kendall';

// 1. Method Invocation
var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {
            return this.manager;
        }
    };

alert(everton.getManager()); // alerts 'Roberto Martinez'

This is the kind of behaviour you would expect coming from an object-oriented background, so no unpleasant surprises here.

Scenario 2 – Function Invocation

Here we are referring to any function which is not declared inside an object. That is, any function which is declared in the global namespace. Using ‘this’ inside such functions actually refers to the global namespace, rather than the containing function. Strange behaviour indeed, and Douglas Crockford actually describes this behaviour as a mistake by the creators of JavaScript. Thus in the example below, we are alerted with ‘Howard Kendall’, rather than ‘Roberto Martinez’.

1
2
3
4
5
6
7
8
9
10
11
// Set global variable
var manager = 'Howard Kendall';
 
// 2. Function Invocation
var getManager = function()
{
    var manager = 'Roberto Martinez';
    return this.manager;    
};
 
alert(getManager()); // alerts 'Howard Kendall'
// Set global variable
var manager = 'Howard Kendall';

// 2. Function Invocation
var getManager = function()
{
    var manager = 'Roberto Martinez';
    return this.manager;    
};

alert(getManager()); // alerts 'Howard Kendall'

So we have established that ‘this’ inside of a method refers to the method’s containing object, and ‘this’ inside of a global function refers to the global namespace. But what is referred to by ‘this’ inside of a function which is declared inside of a method? The answer is – the global namespace, as shown in the example below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var manager = 'Howard Kendall';
 
var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {            
            var innerFunction = function()
            {
                return this.manager;
            };            
            return innerFunction();
        }
    };
 
alert(everton.getManager()); // alerts 'Howard Kendall'
var manager = 'Howard Kendall';

var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {            
            var innerFunction = function()
            {
                return this.manager;
            };            
            return innerFunction();
        }
    };

alert(everton.getManager()); // alerts 'Howard Kendall'

This behaviour is slightly surprising. If we want to use an inner function inside of a method, we can get around the problem by assigning ‘this’ to a variable inside the outer method, as shown below with the ‘that’ variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var manager = 'Howard Kendall';
 
var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {
            var that = this;
            
            var innerFunction = function()
            {
                return that.manager;
            };
            
            return innerFunction();
        }
    };
 
alert(everton.getManager()); // alerts 'Roberto Martinez'
var manager = 'Howard Kendall';

var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {
            var that = this;
            
            var innerFunction = function()
            {
                return that.manager;
            };
            
            return innerFunction();
        }
    };

alert(everton.getManager()); // alerts 'Roberto Martinez'

Scenario 3 – Constructor Invocation

A third function scenario is that of the constructor function, that is, a function which is invoked with the ‘new’ keyword. When a function is invoked in this way, the ‘this’ keyword refers to the object created, even if the constructor function was defined in the global namespace. Therefore, in the example below we are alerted first with ‘Howard Kendall’ and then with ‘Joe Royle’. We refer to ‘this’ inside of a global namespace function when we set the ‘manager’ variable inside of ‘getEverton’, but as we call the function with the ‘new’ keyword, the global namespace ‘manager’ variable is not updated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var manager = 'Howard Kendall';
 
// 3. Constructor Invocation
var getEverton = function()
{
    this.yearFounded = 1878;
    this.inEurope = true;
    this.manager = 'Joe Royle'; 
    
    this.getManager = function()
    {
        return this.manager;
    };
};
 
var efc = new getEverton();
alert(manager); // alerts Howard Kendall
alert(efc.getManager()); // alerts Joe Royle
var manager = 'Howard Kendall';

// 3. Constructor Invocation
var getEverton = function()
{
    this.yearFounded = 1878;
    this.inEurope = true;
    this.manager = 'Joe Royle'; 
    
    this.getManager = function()
    {
        return this.manager;
    };
};

var efc = new getEverton();
alert(manager); // alerts Howard Kendall
alert(efc.getManager()); // alerts Joe Royle

The same behaviour is displayed when we call a method declared on the constructor function’s prototype, and properties can be set on our new object in the normal way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 3. Constructor Invocation
var getEverton = function()
{
    this.yearFounded = 1878;
    this.inEurope = true;
    this.manager = 'Joe Royle';    
};
 
var efc = new getEverton();
getEverton.prototype.getManager = function()
{
    return this.manager;
};
    
alert(efc.getManager()); // alerts 'Joe Royle'
 
var efc2 = new getEverton();
efc2.manager = 'Harry Catterick';
alert(efc2.getManager()); // alerts 'Harry Catterick'
// 3. Constructor Invocation
var getEverton = function()
{
    this.yearFounded = 1878;
    this.inEurope = true;
    this.manager = 'Joe Royle';    
};

var efc = new getEverton();
getEverton.prototype.getManager = function()
{
    return this.manager;
};
    
alert(efc.getManager()); // alerts 'Joe Royle'

var efc2 = new getEverton();
efc2.manager = 'Harry Catterick';
alert(efc2.getManager()); // alerts 'Harry Catterick'

So to summarise constructor invocation, it reflects typical object-oriented behaviour more closely that function invocation. However, it can be dangerous to rely on this approach, as if we forget to use the ‘new’ keyword, our constructor function will be invoked as a regular global function, and we will see the behaviour described above in scenario 2.

Scenario 4 – Apply Invocation

Our final function invocation scenario is the apply invocation pattern. The apply method is defined on the function prototype, therefore it can be invoked on any function. This approach to invocation allows us to provide any object we want to represent ‘this’ inside of the function. Its first argument is bound to ‘this’, and its second argument is an optional array of parameters to be passed to the function. Thus in the example below, we are first alerted with ‘Joe Royle’ and then with ‘Harry Catterick’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {
            return this.manager;
        }
    };
 
var getEverton = function()
{
    this.manager = 'Joe Royle';    
};
 
var efc = new getEverton();
var efc2 = new getEverton();
efc2.manager = 'Harry Catterick';    
 
// 4. apply() Invocation
alert(everton.getManager.apply(efc)); // alerts 'Joe Royle'
alert(everton.getManager.apply(efc2)); // alerts 'Harry Catterick'
var everton = 
    {
        yearFounded : 1878,
        inEurope : true,
        manager : 'Roberto Martinez',
        getManager : function()
        {
            return this.manager;
        }
    };

var getEverton = function()
{
    this.manager = 'Joe Royle';    
};

var efc = new getEverton();
var efc2 = new getEverton();
efc2.manager = 'Harry Catterick';    

// 4. apply() Invocation
alert(everton.getManager.apply(efc)); // alerts 'Joe Royle'
alert(everton.getManager.apply(efc2)); // alerts 'Harry Catterick'

I have attempted here to clearly describe the different behaviours you might see when using the ‘this’ keyword in JavaScript. However, it is a difficult area to describe in plain english. If you find my descriptions confusing I recommend reading Crockford’s book. All the code examples are available to play with at this jsfiddle.

Learning How to Learn

Bachelor hat with glasses and diploma

If you want to learn something about programming which may help you in your career, you are faced with two decisions: what to learn, and how to learn it. And with each decision you are faced with a multitude of options.

I discussed choosing a niche in my last post, and if you are looking for something to learn about, your niche is obviously a good place to start.

But how exactly should you go about learning?

There has been lots of interesting research on the science of learning. There are various study methods and learning techniques on offer. I can’t tell you which learning method is best for you. Everyone is different and your best approach is probably different from mine. What I can do is share some of the approaches I have used over the years, along with some of their advantages and disadvantages based on my own experience.

Approach 1: The Organic Study Method

When I was studying for exams at school, I came across a book by Tony Buzan called Use Your Head. In it Buzan describes what he calls the ‘Organic Study Method’. This is a very detailed approach to learning which involves reading and note-taking. In summary it asks us to do the following:

  • Prepare for a study session by answering a few questions about your goals, how much and how long you plan to study
  • Speed read a book multiple times, at different speeds, rather than just reading normally once
  • Use mind maps to take notes
  • Review your notes at specific intervals following a study period

I largely followed this method in school, and it did seem to work. However, this approach is extremely prescriptive, and thus requires a lot of self discipline. For example, it advises you to review your notes 10 minutes after a 1 hour study session, then for 2 minutes a week later, then again for 2 minutes a month later, and so on. I am put off by the stringency of this method. It is not much fun. I would only use it again if preparing for an important exam, which is not my intention when it comes to learning about programming.

Pros: excellent method for achieving long-term recall.

Cons: prescriptive, complicated, unsustainable for most.

Approach 2: 20 Pages Per Day

Another approach to successful learning is described by James Clear in his blog post, How to Read More. He is less concerned with the mechanics of how you read, and more concerned with the development of a reading habit. His approach is simple: start every day by reading 20 pages of your chosen book. That’s it. By developing this habit you will naturally work your way through many books over the course of time.

Pros: simple and sustainable.

Cons: Not geared towards long term recall or enjoyment.

Approach 3: Spaced Repetition System – Anki

One approach to categorizing learning methods is to divide them into active and passive methods. As you might guess, active learning essentially involves proactively using your brain to solve problems, rather than just passively reading a book or watching a video. Research shows that active learning is more effective than passive learning at achieving long-term recall.

A while ago I became quite interested in the theory of active learning, and downloaded a free application called Anki to help me learn about ASP.NET MVC. To use Anki, you need to come up with quiz-style questions and answers about whatever topic you are reading about, rather than taking regular notes.You input these questions and answers into the software, which then asks you the questions at intervals, spaced according to scientific research on how regularly we need to engage our brains to remember a fact in order to achieve long-term recall.

What I found was that after a while I was spending more and more time answering old questions and less time studying new material. Entering appropriate questions can also be time consuming and can break your flow. Plus it is harder than it sounds to translate material into appropriate questions and answers.

Pros: scientifically proven, good for fact-based learning or exam preparation.

Cons: time-consuming and hard to achieve flow.

Approach 4: Practical Experience

An alternative method of active learning which can be especially useful in learning about programming is to actually code something using the language or techniques you are learning about. In my experience this is the most enjoyable method of learning something, and if you enjoy learning it’s probably more likely to stick and certainly a more sustainable approach. The difficulty is finding ways to apply the various aspects of your subject matter to your project.

A compromise is to follow a walkthrough, which gives you the benefit of comprehensively covering the subject matter, and the enjoyment of coding something up. However, with a walkthrough it is difficult to pick and choose which particular topics within a broader subject area you wish to focus on.

Pros: fun and sustainable.

Cons: unstructured, not comprehensive, hard to pick and choose topics with a walkthrough.

Approach 5: Videos

More video tutorials are appearing on the web every day, on just about any subject you could think of. Pluralsight in particular offers an enormous range of brilliant videos in return for a monthly subscription fee. Simply sitting and watching a video is the ultimate passive learning activity. You barely even have to move your eyes, you can just sit down and watch. If you’ve had a hard day at the office, you will find it easier to sit down and watch a video tutorial than to read a chapter from a textbook. You may only take in 50% of what you see, but this still might be more than you would take in from a book.

As I mentioned earlier, passive learning has been shown to be less effective than active learning, however many video tutorials (including Pluralsight) are accompanied by downloadable files to partially address this issue.

One disadvantage of videos is that you can’t dictate the pace. You can’t speed read or flick through a video.

Pros: enjoyable, easy.

Cons: Set pace of learning. Passive.

Approach 6: Teach It

A final approach to learning is to teach what you learn. I have found this to be a great method for solidifying learning. Many people, including Stephen Covey and John Sonmez, have advocated this method for learning material. It is one of the reasons I started this blog. Teaching forces you to mentally organise information in a way which is clear and understandable, a process which helps to imprint that information to memory.

In order to use this method you of course need to find someone to teach. The most obvious way to achieve this is to start a blog, but this takes time which could arguably be put to better use. If you don’t want to commit to starting your own blog, sites such as CodeProject accept articles on almost any technical topic.

An alternative would be to start offering presentations on topics of interest at work, but again this would take time to prepare.

Pros: it works, enjoyable.

Cons: Not always practical, time-consuming.

My Own Approach

I was going to end this post by telling you my own preferred approach for learning, but I realised that I don’t really have one preferred approach. I tend to switch between these methods and others according to my mood and motivation. Currently I am reading a book and making a few random notes. I am trying to read a little every day or two and making decent progress. Once I am finished with that book I plan to switch to some tutorials and walkthroughs. I might watch a video or two in between. The most important thing for me is to just keep on learning, and understanding the mechanics of learning using methods like these will hopefully help me to do that.

I Choose JavaScript

decision

Recently I’ve been thinking a lot about choosing a niche in software development. The idea has always been at the back of my mind, but now the time feels right to take a gamble and pick a technology to focus my learning efforts on, at the expense of other potentially interesting and fun technologies.

The first I read about choosing a niche was in Chad Fowler’s book, The Passionate Programmer. In the book, Fowler gives tips to developers on how to get the most out of their careers. One of his tips is to ‘Be A Specialist’. He suggests that we should really try to deeply understand one technology in particular, to give us a competitive advantage. If your interviewers are looking for someone who knows Java, and you’re truly an expert on the ins and outs of everything to do with the language and the JVM, you’re clearly going to have an advantage over many other candidates.

The obvious cost of focusing on a single technology is that you may become rusty in other areas. But if we are clever with our time I don’t believe this needs to be the case. We might never reach the hidden depths of other technologies, but we can certainly stay in touch with them, and understand their advantages, disadvantages and capabilities. Just because you are an expert in Java, that doesn’t mean you won’t have time to monitor what is happening in the world of .NET, at a high level at least. You may even decide to play with C# for a week, just to get a feel for the language. But your longer term goals will be Java-related. You will have a far deeper understanding of the JVM than the CLR, but you might know what the CLR is and how it differs from the JVM.

Other than just improving your marketability, I believe there are other reasons why it is advantageous to choose a niche to focus on.

Firstly, by getting under the hood of any technology, we will find ourselves learning things which relate to other technologies. By learning about the JVM, for example, we will learn things about virtual machines in general, including the CLR. If we learn about the details of JavaScript, we will learn something about functional programming.

Secondly, I have found that learning about a topic in detail is far more rewarding than just skimming the surface of a number of topics. As you go deeper and deeper, you start to get a feel for the technology as a whole, seeing the whole gestalt and how different components and features interact with one other. You will start to think about how it was invented, and what its creators were thinking when they designed it. You may even start to appreciate the beauty of a language or technology.

John Sonmez has written and spoken extensively on the importance of choosing a niche for software developers. In one of his articles on becoming a specialist, he correctly identifies the number one reason why most programmers don’t consciously choose a niche to focus on.

Fear.

Committing to one particular path in your career, or indeed in life, is scary. We like to avoid doing this, preferring to leave our options open. What if we make the wrong decision? We are scared of failure, scared of getting it wrong, so we cycle through a number of technologies without ever gaining a deep understanding of any of them. This is also a fundamental reason why most people don’t set themselves specific goals. We are scared of picking the wrong goal, so we don’t pick any. However, it is far better to choose and start moving towards the wrong goal, than to stand still and just react to circumstances. If we get moving towards a goal, and it turns out to be the wrong one, we can adjust accordingly and will almost certainly  have learnt something along the way.

Brian Tracy has said:

The great secret of success is to do fewer things but do more important things, and do more of them, do them longer, and get better at them.

The key is to learn to focus. If you are currently spending 1 hour a week reading random programming blogs, and 10 hours a week on facebook and twitter, then by reprioritising your time, you could not only become a specialist in your chosen area, but you could also improve your understanding of other technologies.

I am not saying that facebook and twitter are a waste of time. There is more to life than programming, and I certainly wouldn’t advise anyone to spend every spare hour trying to become a better programmer. But I notice that some people definitely use social media excessively, indeed I have been guilty of this in the past. In order to make better use of our time, we need to think about what we really want to get from our lives and to set some goals which align with this. If we then regularly remind ourselves of these goals, and spend some time working towards them, we will have something to show for our time, other than a littered facebook page.

So what niche have I chosen to focus on myself? Having considered my options, I have decided to work towards becoming an expert in JavaScript, for a number of reasons.

The web is here to stay, and I struggle to imagine a world where JavaScript has been replaced by an alternative client-side language. On the contrary, JavaScript is growing in importance with the evolution of exciting frameworks such as Angular and Node.

I have worked with JavaScript on and off for the past 10 years, but have never really considered how it works at a deep level, or how to get the best out of it. My plan is to firstly gain this knowledge, starting by reading JavaScript: The Good Parts. Once I have a deep understanding of things such as closures, prototype inheritance, and JavaScript patterns and best practices, I intend to move on to learning about a framework in depth, which will probably be Angular, and see where that takes me.

Arguably the most important factor in my choice is that I really enjoy working with JavaScript due to its flexibility and mobility. I could easily work on a simple JavaScript project from anywhere in the world. All I need is a browser, and sites like jsfiddle really help. I don’t need to install a framework or an IDE And there is a lot to learn.

With my decision in mind, expect to see a few JavaScript-related posts over the next few months, as I learn new things and adjust my course. I have made my choice, I invite you to do the same.

Code Smell Confessions

Code smells offer us a convenient way to identify, classify and address bad code.

The phrase was first coined by Kent Beck, while helping Martin Fowler with his famous book, Refactoring. A code smell is an indication of bad code. It is something that is easy to spot quickly, and which probably tells us that the code could have been written in a more helpful way.

Bad smell concept - peg on male nostrils over black

How can code be helpful, you might ask?

Helpful code will not be too difficult for future programmers (including your future self) to modify, debug, refactor or extend. It helps your future self and others. It is a sign of a considerate programmer, who not only prevents future headaches by allowing code which can be easily updated, but also creates code which can be quickly updated. This allows your system to include more new features and bug fixes per release, which means a competitive advantage for your product.

The most well-known list of smells comes from Fowler’s Refactoring book. If you don’t want to buy the book, two good starting points for learning about this topic are A Taxonomy of Code Smells and SourceMaking.

The 3 Worst-Smelling Smells

The three code smells I encounter most frequently are Long Method, Large Class and Duplicated Code.

Long methods can be nightmarish for a number of reasons. They are difficult to unit test, difficult to read, and frightening to modify. The beauty of short methods, particularly if they are well named, is that they allow our brains to better process what the code is actually doing. If we can’t get past this essential first step in understanding someone else’s code, we are going to struggle.

The solution to the problem of a long method is to break it up into smaller methods. Resharper and Visual Studio offer ‘Extract Method’ tools which  can help with this. To ensure we don’t break anything, it is preferable to thoroughly unit test the method before breaking it up, although this can be more difficult than it sounds, as explained by Michael Feathers in Working with Legacy Code.

Large classes often indicate a violation of the Single Responsibility Principle. If a class does a lot of things, it will have many potential reasons to change. Each change to the class risks breaking something in the same class, something which may be unrelated, leading to a system which lacks robustness.

Code duplication and large classes often co-exist. If you find a large class there is a good chance it will contain some duplicate code. If you need to change how that code works, you need to find multiple places in your codebase which need changing. Solutions which are littered with duplicate code are also harder to understand and are generally unnecessarily bloated.

Causes of Code Smells

I can think of three distinct reasons for the existence of code smells in our codebases: ignorance, laziness and denial.

Firstly, ignorance. This refers to programmers who don’t realise what they are doing. They have never been educated on best practices and code smells.  Or they may know they are doing something wrong, but they don’t appreciate its consequences. For these programmers, the answer is education, and the topic of code smells is a good place to start.

The second common cause for code smells is laziness. These programmers know they are doing things badly. They appreciate that creating large classes and long methods is not the best way of doing things, but they do it anyway, because they can’t be bothered applying the extra mental effort to do things correctly. What we need to realise is that doing things the best way is just a habit we need to learn, and that it is well worth the effort in the long run, not only for the product you are working for, but for your own professional development.

Laziness can also be a cultural issue. If your teammates don’t make an effort to create high quality code, then you are obviously less likely to do so yourself. Conversely, if everyone else avoids code smells like the plague, then psychologically you are going to resist being the only person who writes bad code. This is one of many reasons to surround yourself with better, more experienced programmers where possible.

A third precursor for code smells is denial. This most commonly occurs when a programmer feels under pressure to hit a deadline, and so frequently opts for the quick and dirty solution, suppressing any underlying feelings that they are not doing things the right way. This most commonly is a cultural issue, where it is deemed more important to produce anything quickly, than to produce something of good quality which takes a slightly longer time.

In actual fact, the observation that doing things the right way takes longer is often a myth, at least in the long run.  The answer here is to get into the habit of producing high quality code, so that you can do so quickly and without too much extra effort. Improving your estimating skills will also help avoid situations where you feel under pressure to deliver something quickly.

Final Thoughts

Martin Fowler makes an excellent point with regards to code smells. Just because a method is long, or a class is big, that doesn’t necessarily mean that there is a problem that needs to be addressed. It may be that fixing a code smell by refactoring would be too risky. Or it may be that a quick and dirty solution is in fact the best approach. Perhaps you are working on a throw-away project where meeting a deadline is genuinely more important than producing good quality code. Projects like this do exist, although they are few and far between.

I believe that the three code smells listed above: Long Method, Large Class and Duplicate Code, should be an essential part of any elementary programming course. Such courses tend to focus too much on syntax and not enough on language-agnostic principles. At the very least, programmers entering their first job must have an understanding of basic code smells such as these.

With experience and understanding of course, our ability to intuitively judge a situation will improve, and we will know when it is right to refactor and when it is not. Programming is a never-ending learning experience, which is one of the reasons it is such good fun.

Certification? Not For Me

happy graduate dog holding a big diploma

Microsoft offer a wide range of certifications for developers working with their stack. These are divided into five categories:

1. Server – Windows Server, Exchange Server, Lync, Sharepoint

2. Desktop – Windows

3. Applications – Office, Office 365, Microsoft Dynamics

4. Database – SQL Server

5. Developer – Visual Studio, Windows Phone, Sharepoint Applications

Within the ‘Developer’ category there is one certification in particular which seems to match my area of work, the MCSD: Web Applications certificate. It covers three aspects of Microsoft web development:

1. Programming in HTML5 with JavaScript and CSS3

2. Developing ASP.NET MVC4 Web Applications

3. Developing Microsoft Azure and Web Services

This sounds appealing. All three are areas I would like to gain expertise in, and skills which I would expect to be useful in my day-to-day work over the next few years.

But all things considered, I very much doubt I will ever bother with certification. Before I go into the reasons why, let’s consider some of the benefits.

Broadly speaking I believe there are 4 potential advantages to going down the certification route.

1. Direction.

The task of learning about a particular area of technology can be daunting.

Let’s say I decide I want to become an expert in web development. Where do I start? HTML, CSS, ASP.NET, MVC, PHP, Java, JavaScript or something else? What’s more, each of these presents additional choices. Do I read a book? If so, which book? What about online tutorials, blogs and articles?

In the age of information we are faced with a multitude of learning options, which means that even when we do take a gamble and make a choice, as soon as the going gets tough it is all too easy to be distracted by an alternative, and in this way never to learn much about anything.

Focusing on a certification provides us with direction. We have a syllabus consisting of a list of topics. All we need to do is work our way through it.

2. Satisfaction.

Having spent many weeks or months studying hard, learning about your chosen area, completing chapters, exercises and tutorials and making notes, do you not deserve the satisfaction of passing an exam and holding a certificate in your hand?

We’re all human and we all feel a sense of satisfaction from achieving things. Certification is indeed something to be proud of. It shows you have put in a degree of work and proves you know something about something. You can frame your certificate and put in on your wall, update your linkedin profile and your CV, and bask for a short while. Maybe treat yourself to a scotch or a cigar.

Satisfaction arising from achievement should not be trivialised. It is important.

3. Learning Stuff

Whatever your thoughts are on certification, if you work towards it and pass your exam, you will undoubtedly learn a thing or two along the way.

In our industry it is vital to keep on learning if you want to stay ahead of the game, and certification can be a way to trick ourselves into acquiring new skills and knowledge.

When I was learning to drive, I didn’t spare much thought for how much it would improve the quality of the rest of my life, I just wanted to pass my test and get my license. Looking back, this was one of the most valuable learning experiences I have had. In a similar way, if we focus on obtaining certification, we will probably learn things along the way which will help us in our day-to-day work.

4. Employability.

Whether or not a certification will impress employers enough to give you the edge over your competition is an interesting and difficult question. But we can be fairly certain that it won’t do your chances any harm, and if you are lucky your interviewers will consider your certification to be an indication of your ability and your suitability for the role in question. They may see it as proof that you are a hard worker, you care about your career, and you understand how to solve programming problems.

So given all these benefits, why have I decided that certification isn’t for me?

In a nutshell, it is simply that preparing for it would take up too much of my time, time which I would rather dedicate to other pursuits.

Let’s consider again the certification which I would most likely choose to work towards – the MCSD: Web Applications certificate. This requires candidates to pass three exams, and for each exam there is a relatively long and detailed syllabus. If I were to go down this route, I would want to do it properly, and I estimate it would take me between 40 and 60 hours of study for each exam. That adds up to around 150 hours of study, to work into my schedule alongside my full-time job and other commitments.

I do dedicate time, money and effort towards my career outside of my paid working hours. I write this blog, I read books, blogs and articles, and I play with and practice using new or interesting technologies.

But not only do I believe that I gain benefits in each of the four areas listed above in this way, but I enjoy myself at the same time.

I am not too restrictive about what I read, or how I learn. I am just vaguely aware of the impact a particular choice will have on my career. I like to be spontaneous in my learning, and this helps to ensure that I keep on learning and don’t get bored. This week I am reading from JavaScript – the Good Parts, but next week I may decide to learn about something completely different.

If I were to pursue a certification I would need to be convinced of two things. Firstly, that it would present me with a clear advantage in my career, and secondly, that I would enjoy the process of studying for it. At this moment in time I am not convinced of either, so I will continue to learn about my trade in a more creative and enjoyable manner. It would be nice to be able to list a certificate on my CV, and to have that achievement under my belt, but like most decisions this really comes down to a cost-benefit analysis, and for me right now the benefits are greatly outweighed by the costs.

The Liskov Substitution Principle: Keep Your Promises

All programmers should be familiar with the five SOLID design principles. Along with Design Patterns, these are the most important things to understand for anyone wishing to design good (i.e. loosely coupled and highly cohesive) object-oriented software systems.

Of the five principles, the one which people have trouble grasping is the Liskov Substitution Principle.

This principle has been described in many ways by many people. Let’s begin with the technical and original description from Barbara Liskov, as referred to in Uncle Bob Martin’s paper on the subject:

What is wanted here is something like the following substitution property: If
for each object o1 of type S there is an object o2 of type T such that for all
programs P defined in terms of T, the behavior of P is unchanged when o1 is
substituted for o2 then S is a subtype of T.

If you’re not familiar with the principle and you’re anything like me, this statement will make your head hurt.

A much better starting point is Uncle Bob’s interpretation from the same paper:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

Or another description by Uncle Bob, from a podcast interview by Scott Hanselman:

The caller of the original entity [base class] should not be surprised by anything that happens if one of the subentities is substituted.

If I had to describe the principle in a sentence, it would be this:

Derived classes must keep any promises made by base classes.

Promises, Promises

So what are these promises that can be made by a base class?

To understand OO design principles and patterns, it is helpful to always think of your code as being part of an API, to be used by clients (i.e. programmers) who you have never met. Any property or method not declared as private is accessible to these clients, who might try to use your API in odd and unexpected ways. You obviously want to minimize the number of bug reports and support calls raised by them. So how can you do this?

One way would be to ship your API with detailed documentation, specifying how it should be used. What values it expects to be passed, and what exceptions it throws, for example. Your clients can’t see your code, they can only see the method signatures exposed by your API, but they can read your documentation to see how to use it in order to get the desired results.

A good approach for structuring this documentation would be to think in terms of Design By Contract, which demands the declaration of three types of promises for each method: preconditions, postconditions and invariants. Together these form a contract for each method.

Close-up image of a firm handshake standing for a trusted partnership

A method’s preconditions specify the conditions under which it promises to perform its task. As a simple example, consider a method which returns the square root of a number.

1
2
3
4
5
6
public double SquareRoot(double x)
{
 
//...
 
}
public double SquareRoot(double x)
{

//...

}

The precondition of this method might be that its argument is greater than or equal to zero. By specifying this precondition, the method relieves itself of all responsibility for what might happen if a negative number is passed to it.

A method’s postconditions specify what the world will look like after the method has completed. In the above example, the SquareRoot method might promise that it will not throw an exception, and it will return a value which is the square root of its argument, provided of course that its preconditions have been met.

The method’s invariants specify which properties it will not change during its execution. The SquareRoot method may promise as an invariant not to modify any properties exposed by any class.

Combining our preconditions, postconditions and invariants, the method makes the following promises to its users:

If you pass me a non-negative number, I promise to pass you back its square root, without changing the state of this or any other class. But if you pass me a negative number, I can’t promise anything.

Or to generalize the nature of a Design By Contract promise:

As long as these conditions are true, I promise to behave in this way.

Back to Liskov

Returning to the Liskov Substitution Principle, I said earlier I would describe it as follows:

Derived classes must keep any promises made by base classes.

The promises I am referring to here are the preconditions, postconditions and invariants defined, either explicitly or implicitly, by the base class.

To be more specific, in order to adhere to the principle, a derived class must follow 3 rules: it must not strengthen a precondition, it must not weaken a postcondition, and it must preserve invariants.

A condition is strengthened when it is made more restrictive, and it is weakened when it is made more lax.

In our square root example, if a derived class specified in its preconditions that the method will only behave as promised if the argument is greater than 10, then this would be a strengthened precondition and a violation of the LSP. The base class promised that it would handle any non-negative number, so the derived class is breaking the promise made by the base class.

However, if the precondition was weakened, by specifying that negative numbers are in fact allowed, and will be handled by the throwing of a specific type of exception, then this is not a violation. The promise made by the base class – that it would handle any non-negative number – still holds true.

The Square-Rectangle Example

One example commonly used in describing the LSP is that of the square and the rectangle.

A programmer observes that a square is a type of rectangle, and so defines a Square class which inherits from the Rectangle class. This seems reasonable. However, the problem arises when we consider a method, SetHeight, which exists in both the Rectangle and Square classes.

In the Rectangle class, one of the invariants of the SetHeight method is that it will not modify the class’s Width property. But in the Square class, it seems perfectly correct for the SetHeight method to set both its Height and Width properties. In this way the LSP is violated, as the derived class does not preserve the invariants specified by the base class.

The Electric Duck Example

A second common example is that of the electric duck. It may seem fair to conclude that an electric duck is a type of duck, and therefore the class ElectricDuck should inherit from Duck. However, consider a Swim method  defined in both classes. In the Duck class, the Swim method has a postcondition which promises to always set a property, IsSwimming, to true. However, in the ElectricDuck class, the IsSwimming property is only set to true if a separate property, IsTurnedOn, is true. In this way the method’s postcondition is weakened. The promise of always setting IsSwimming to true has been broken.

A Word on Inheritance

The Liskov Substitution principle relates to inheritance, which is one of the three standard features of an object-oriented programming language, the other two being encapsulation and polymorphism. I learnt about these three OO features at university, so I was surprised as a junior programmer to read, in Head First Design Patterns, about the dangers of using inheritance in systems design, and of the Composition Over Inheritance principle. The square-rectangle and electric duck examples show that the commonly cited “is-a” rule for inheritance can be problematic. A square is a rectangle, and it can be argued that an electric duck is a duck (depending on how you define a duck). But as we can see, structuring your program according to these relationships can be problematic. Inheritance can be extremely useful, but some programmers are too eager to use it. It should be used with caution.

Final Thoughts

Like all of the SOLID design principles, I see the Liskov Substitution Principle as a principle of integrity and respect. Imagine that your public methods and properties will be used by other programmers, and design your code so that they will not encounter any nasty surprises. Noone likes calling a method only to find it causes some unexpected behaviour. Save future programmers, including yourself, the headache of debugging and ensure your code keeps its promises.