A couple of principles when learning how to code.

By | May 12, 2012

Principle 1.
Always have a clear image of what you want to do BEFORE you start writing your code. Then break it down in logical instructions – making an algorithm.  An algorithm is a step by step instruction on how to solve a specific problem. You might think of it as a recipe. If you want to bake bread – you don’t just start shoving any eatable stuff you find into the oven without a plan. First you decide what kind of bread you want to make, then you find out what ingredients is needed, how much and in what order they are added.

So basically – if you can’t solve the problem with logic you can’t solve it with code.

For example:

 You want to write a piece of code that finds the mean (average) of three numbers supplied by a user.  Before you start writing the code, you must of know how to calculate the mean of three numbers. The solution to this mathematical problem is of course (n1+n2+n3) / 3. Now I just have to break it down into step by step instructions, like this:

1. Gather three numbers from the user
2. Add them together.
3. Divide the sum by three
4. Output the sum on the screen

Now I can easily translate this simple algorithm to code in any language, for example PHP. Review your steps and think about how to solve this in code;

Step 1. Make a form with three textfields.
Step 2 & 3. Take the three values from the POST array, add them together and divide by three.
Step 4. Echo the result.

if (isset($_POST['submit'])) {
	$n1 =$_POST['n1'];
	$n2 =$_POST['n2'];
	$n3 =$_POST['n3'];
	$sum = ($n1 + $n2 + $n3) / 3;
	echo $sum;
<form action="" method="post">
	<input type="text" name="n1" />
	<input type="text" name="n2" />
	<input type="text" name="n3" />
	<input type="submit" name="submit" />

At this stage it’s easy to refactor the code to a more efficient solution. The calculation could fit in just one single line:

echo ($_POST['n1'] + $_POST['n2'] + $_POST['n3']) / 3;

Principle 2.
If you use code that you find online (like on a blog or a forum), make sure you learn what every single line of code does. It will take a bit of time, and might demand some hard work – but having code in your application that you don’t really understand is a bit like playing the lottery.

Getting code to do exactly what you want will be very hard if you don’t know exactly what is does.

Also, this is maybe the best way to learn how to code.

Leave a Reply

Your email address will not be published. Required fields are marked *