Thursday 28 January 2010

Do as I say, please

Recently I have been thinking about the old adage 'Do as I say not as I do'. This has been on my mind a lot since my recent entry on the usefulness of variables and their use in combating the problems caused by magic numbers

This is sound advice (trust me) but the thing is, I, as well as many other programmers, are guilty of breaking this rule, a lot (even though they'll tell you they don't). We will probably regret breaking it and curse ourselves for taking the short cut, but it does happen.

In an attempt to maintain the use of such a rule, one must try to apply it at all times, unless a set of requirements are met in which it is appropriate not to do so. So given a certain context, the rule can be broken, but one should ensure the reasons for breaking it are sound and justified. So an example of where using magic numbers may be acceptable is rapid prototyping or throw away prototyping where the object is to get something working as quickly as possible, and the code does not need to be maintained or reused. This would be a time where the rule does not need to be followed to the letter, but you can bet at most other times you should take heed of it.

Other examples of certain approaches which are regarded as dangerous or bad practice are things such as multiple inheritance or use of the goto statement. You are told to avoid such things (which I personally would!) but again you'll find times where it may be appropriate to apply them. Emphasis is placed on them to ensure that if you ever find your self having to implement such a design, you are acutely aware of the potential traps you can fall into, and why they are dangerous to use. (It's also worth adding a host of comments to explain your rationale to other friendly programmers!)

I guess, putting it as plainly as possible, you should take these things with a pinch of salt. These ideas are usually a good thing to follow, especially when you are starting out, but there will always be exceptions, the trick is knowing what they are and when to use them.

Monday 25 January 2010

The Life Of A Programmer


Magic Numbers

int _health = 100;
_health -= 5;

What do you see?

Firstly, If you have no idea what the preceding lines mean, you're probably better off not reading the rest of this post as it won't mean a whole lot to you. I'd go and check facebook if I were you, I am sure something more interesting is going on over there anyway, however if you change your mind you are welcome to stay.

If you do understand what on earth I am going on about (Greeting fellow nerd), and you see a perfectly acceptable line of code, please get out of my sight and write a console application that prints the line 'I am sorry for my hacking' 100 times. I'm kidding, please don't do that, but please do read on to see why you are quite mistaken.

What you should in fact see is a terrifying example of hacky code. The above line, while maybe, (and I mean maaaaybe) acceptable in a program a few hundred lines long, it is in fact the bane of a programmer's existence when the program begins increasing in size and complexity.

What the '5' represents in that line of code is a magic number, an arbitrary value that can easily and accidentally be changed (often with disastrous consequences), or prove extremely difficult to change if there are lots of them (I'll come to that later). In your programs you should never have values like this appearing in your code. When ever you see a value like this it should scream at you with the sound of an opera singer's wail after a grand piano has just been dropped on their toe.

Whenever you see a value like this, you should immediately think exactly what it is meant to be representing, and then replace it with a variable!

Variables are fantastic things and should be used as much as possible. What they allow you to do is represent a type, be that an integer, a floating point value, or one of your own classes, with a piece of text, that you the programmer can easily process and understand. As the name is associated with a type you know exactly what kind of information it represents too. So for example, an improvement on our previous example is:

int _health = 100;
int _damage = 5;
_health -= _damage;

Immediately it is clearer what is happening, but that really isn't the best part. Imagine if damage appears in multiple places all over your program, suppose you then decide that you want the damage to be '10', not '5' any more (I told you I'd come to it later). If you were not using variables you would have to search all over the program to find every context where '5' was being used to change the health, and updates it's value to '10'. This can easily lead to bugs, and take an inordinate amount of time finding every '5'. If instead you had used _damage, you need only change that value once where it is declared, and all the other values will be updated accordingly.

We can also declare variables with the const keyword if you do not want the value to change. const tells the compiler that the value cannot change after the variable has been defined. This stops you the programmer from accidentally changing the value later in the program, possibly introducing more bugs into your code.

There are many more reasons for why variables are useful, and a myriad of examples, but I won't go into them just now. I hope you found my rant vaguely informative, if not mildly entertaining. I am now going to double check my code and I fear I'll eat my words when I see all the magic numbers staring back at me.

Sunday 24 January 2010

Drawing pictures

While working on code, you often find yourself confronted with problems that are quite tricky to get your head around. Such problems might range from things like relationships between classes, to detailed path finding algorithms. In my (short) experience I have found a sure fire way to help in defining such problems, and it's simple; draw a picture.

'Wait!' I hear you cry, 'I'm a programmer not an artist, why the hell do I need to draw anything!?'

Now don't get me wrong, I am not saying you should create a work of art, far from it, what you want is a crude abstraction of the problem facing you, and that is more often than not, best achieved with the aid or a picture or diagram.

By creating an abstraction of the problem, you immediately give your brain a chance to breathe, and absorb the information in a new way. It helps you visualise the problem, and allows you to hold it in your hands, add notes to it and see it in the real world. It takes a load off the old grey matter too so you don't have to be storing all the information you need in your head at once.

Universal Modelling Language (UML, of which I am sure I will talk later) is a fantastic tool for this when describing class relationships, program flow and so forth (it's also great because as it's a standard, if you implement it correctly, other people who know UML will understand exactly what you mean) But I'm not just talking about this, I am talking about any problem at all. It could be something mathematical,  some kind of behaviour, some process; if you attempt to draw a picture of what is happening, or create some pseudocode for the underlying process, it will help no end in your understanding.

The saying goes that a picture is worth a thousand words, in programming, I'd say a diagram is worth 10,000 lines of code.

Now get those pens out and start scribbling.

Saturday 23 January 2010

C++ Errors

This isn't a proper blog entry but I felt I had to say something about this small (GINORMOUS) problem I encountered.

I'll set the scene for you, it was a quiet Saturday morning, I was leisurely sipping coffee as I went about re-factoring some of the code I had written the night before (which now looked terrible compared to what I remembered writing). I had made a few changes, checked over the file I was working on to ensure there weren't any glaring errors such as missing semicolons (Hey, we all do it okay). I hit build, and to my sheer horror, 161 errors leapt at me from the output window.

Now when this happens it is usually something easy to spot like a missing curly brace, and you can quickly fix the problem, but maybe because I had only drunk half my coffee, and it was now tepid and undrinkable, I could not for the life of me find the problem. I poured over the source code, looking in every file that was referenced by the one I had changed. Had I accidentally hit a key while I was changing pages? I couldn't find anything.

Thirty minutes later, with half the hair I had when I started now missing and tears welling in my eyes, I was ready to give up and become an art student (sorry art students). Then, just as all hope seemed lost, I caught something out of the corner of my eye, could it be? There staring me in the face was something that almost made me tear out any remaining hair I had. A class called Projectile was being declared, however it had somehow acquired an 's' on the end, so it was now 'Projectiles'. This typo had caused Visual Studio to throw up 161 errors!

I deleted the 's', hit compile, and Wooosh, everything was working again and the world was lovely...

That's life I guess, and another lesson learned that proof reading, perhaps more so in code than anything else, is intensely important. Now I am off to buy a hat to cover up the bald.

Friday 22 January 2010

A moment for a joke

Here is an attempt to raise your spirits on a dreary Friday afternoon, a poor programming joke that came to me while writing some code:

How many programmers does it take to open a can of sardines?

10, 1 to open the can, and 9 to tell him how much more efficiently he could have done it.

Drum Roll, Symbol, Applause

( Edit: A better joke with thanks to James in the comments:

How many programmers does it take to open a can of sardines?

10, one to open it, and one to explain binary.

I doff my cap to you good sir )

Or the exact opposite..

With regard to my previous post about the use of comments and the importance of clear maintainable code, please see this http://freeworld.thc.org/root/phun/unmaintain.html

It is a brilliant article on the best ways to create completely unreadable and unmaintainable code to ensure you are the only person who can understand it, by the time you're done chances are you won't be able to understand it either.

Each to their own

(Thanks go to Paul Harsent for the link)

Thursday 21 January 2010

Comments, Comments, Comments

From the title you may be guessing this is a crass attempt to get you, the poor bugger reading this, to post a comment at the bottom of this entry commending my awesomeness, but my friend it is not. Instead I thought I might briefly talk about the importance and usefulness of comments in code.

Often you hear from hardcore coders that commenting is for wimps, this sentiment comes from the same group of programmers who follow the mantra, 'If it was difficult to write, it should be difficult to read'. While these people may be justified in their beliefs, and lets face it, they do sound cool, in the long term it really isn't a good idea.

Now don't get me wrong, I am not condoning such enlightened commenting as:

                                         int val = 5; // val now equals five

This is clearly irrelevant, and only serves to de-emphasize comments that may actually be useful later on. I am talking about a brief description above a short piece of code or algorithm that briefly describes what it does. This could be as simple as //calculate shortest distance, or //rotate according to new position.

Now you could argue in these scenarios that the best idea is to create functions or methods with meaningful names such as CalculateBalance() or UpdatePosition(). This is a great idea, and often it is sufficient, but occasionally, especially while you are in the process of writing code, when you return to it, instead of having to skim through it and quickly figure out what it is doing, you can see the little comment descriptor and know exactly where you are. I have found this immensely useful when writing a method, and then when I know exactly what it is doing, I can give it a useful name so I can easily identify it.

Comments are also great for explaining your code to peers and other people who will be using your code. If you have used a certain hack or cool trick, be sure to point it out to the next guy so he doesn't have to rack his brain for why on earth you did it, remember the next guy can easily be you returning to your code a week later, finding a jumbled heap of squiggles staring back at you instead of the elegant code you thought you wrote.

Now this might be a point of contention, but I also love using comments to break up code, it makes it more readable (and more colourful if you are using lovely Visual Studio) and can make scanning through pages of code much easier.

//************************ I love comments *****************************//

void WriteComment( std::string comment );

//************************ I love comments ***************************//

You can't tell me that doesn't look lovely.

So there you go, why comments are awesome, now if only you could write a comment and have it magically turn into code, that would be sweet!

Wednesday 20 January 2010

Tower Defence! and Design

Okay, I am going to attempt to make a start at this blog by talking about a project I am working on at the moment. Points go to those who guessed from the title that it is indeed a tower defence game.

One of the problems I encountered when starting the project was the sheer number of things you need to create a game, not just a cool tech demo, but a real game. I am going to assume that if you found your way here there is a good chance you have played a tower defence game, it might not seem like much, but when you start adding up all the features you realise there are enemies, towers, map, user interface, artificial intelligence, state management, input, sound, graphics (and networking in my case ) 'Audible Gulp'.

Now each of these in isolation is fine, but the trick with the game is there are relationships between these objects, and certain objects have to interact and update other objects accordingly, and in order for this to happen you need lovely code to properly initialize, update and finally clean up all of these things. The trouble is how you go about doing this.

Enter Software Engineeing! If you talk to anyone who has written a large piece of software they will tell you design is king. It is much better to spend longer on the design, and get it right, than start implementation, and have your shoddy plans fall apart. The only problem is, designing something, when you don't really know exactly what you want, or know the best way it should work, or how it should fit together, without a great deal of experience, is extremely difficult. What exactly do you do then...... Enter Tom!

Now I am in a small conundrum where I know design is important, and I do have a (flimsy) design, but there is also a desperate need (especially given the impetuousness of youth) to see results, and that can happen quickly if you throw design to the wind, and break open your tool bag of tricks to get stuff up on screen. This is intensely satisfying, but often you'll find that your hacking has created a hole (sometimes a black hole) that is now inescable and you find nothing else will work with your new change. The design falls apart and you are left with super glue and nails where girders and beams once stood.

This is the problem with writing code, when you are dealing with something that is intangible, you need a grasp of the structure and design of the software, not just small parts in isolation of one another. But to create that amazing design, you need to know what designs work, and when to use them, and to know this you probably have to fall, at least a few times.

I apologise for my mad ramble, but I find it is a difficult subject to talk about. I do think that it is a trap all too many programmers fall into, but it is one laid so expertly one can hardly blame them. In working on this project I hope to strike some kind of balance, I'll let you know how it pans out!

Tom's Tech Blog

Hello people of the internet!

I'm not quite sure how you found your way here but I'm glad you did. Please pull up a chair, I'll put the kettle on. Coffee or tea? Milk, sugar? Sorry I digress...

This blog is intended for those of you who share my interest in software engineering and programming. I hope in the coming months you'll find an array of interesting things here. I intend to post about what I'm working on, things I'm reading, and hopefully links to other cool stuff on the web.

I think this could be the beginning of a beautiful friendship.