UNIT 1 - ⇑ Fundamentals of Programming ⇑

← The Role of Variables Fundamentals of Structured Programming One-Dimensional Arrays →


You should already have seen how you can use structure tables, structure charts, hierarchy charts and procedures/functions in breaking down a complex task. This section will look at how to write the best formed and most readable code we can.

If you want to be a good programmer (and get good marks in the exam) then you have to make sure that your code is easily read by other people. There are several things you should try and do when coding:

Use procedures that execute a single task edit

Each procedure / Function does a single thing, such as calculate the current health of a player in a game. This means you can then use them as building blocks to build bigger solutions. If you make your procedures / functions do too many things at once, then they are very hard to re-use in different projects and harder to test.

Use procedures/functions with interfaces edit

  • Breaks the problem into chunks
  • You can test each separately
  • You can reuse code

Use sensible variable datatypes edit

Make sure that the datatype you use are sensible. You will get marked down for using the wrong datatypes in your database tables and variables.

For example: If you are recording the total number of chocolate bars in a shop you don't need to use a Long or Float, you can only have whole numbers of chocolate bars and it is unlikely you'll have over a few million items. Use an Integer!

Meaningful identifier names edit

When you are declaring parts of your program and you return to the code some time later, you want to be able to understand what each variable, procedure and function does without having to trace out the code. The easiest way to start doing this is to name them correctly:

Use sensible variable names edit

If you are using variables to store things they must have a name that makes sense so you know what it does when you read its name in your code.

For example: If you are recording the total number of chocolate bars in a shop you don't want to use a name like variable1. What does variable1 mean? Use a sensible name such as NumChoc.

Use sensible Function/Procedure names edit

If you are creating subroutines to process things in your code make sure you give them a sensible name so that people know what they are doing when they see them in the code.

For example: If you have written a piece of code to calculate the average price of a chocolate bar then don't call it FunctionA(), what does FunctionA() mean?! Call it ChocAverage().

Try to stick to one naming convention edit

If you are using lots of variable names and function names, stick to a single style for naming them. If you use lots of different conventions things are going to look ugly. Wikipedia guidance

For example:

  • firstName, lastName, calculateDoB, numLegs
  • FirstName, LastName, CalculateDoB, NumLegs
  • First_Name, Last_Name, Calculate_DoB, Num_Legs

Don't make your names too long edit

Long variables can be very hard to read and much easier for you to make mistakes when writing them, try to shorten things where possible.

For example:

Too Long Just Right
ThisIsYourFirstName FirstName
the_value_of_a_chocolate_bar ChocVal

Indent your work edit

A lot of programming environments help to indent your code automatically and you should be able to find one for the language you are using. Indenting helps people to read and understand your code quickly as it clearly shows the structure of functions, procedures, selection and iteration statements. For example the following is very hard to read:

int main(int argc, char *argv[])
{
...
while (x == y) {
something();
somethingelse();
if (some_error)
do_correct();
else
continue_as_usual();
}
finalthing();
...
}

If you indent it is becomes much easier to read:

int main(int argc, char *argv[])
{
    ...
    while (x == y) {
        something();
        somethingelse();
        if (some_error)
            do_correct();
        else
            continue_as_usual();
    }
    finalthing();
    ...
}

Use comments where necessary edit

Some of the best written code doesn't need comments because if you have structured it correctly and used all the proper naming conventions it should be pretty easy to read. However for the code you are writing you should put some comments to explain what each section does.

'this function takes an array of prices and outputs the average
function calculateAverage(num1(20) as integer)
{
    'add all the numbers together
    while ...
          ...
          ...
    end while
    
    console.writeline(average)
}

The advantages of the structured approach edit

  • Easy to read and fix code
  • Problems broken down into easy to manage chunks
  • procedures / functions are reusable, you can use them in different projects.
  • You can test modules individually
Exercise: Structured programming
sub calcEverything(byref a as integer, byref b as integer, byref c as integer)
  dim total, avg as integer
  total = a + b + c
  console.writeline("the total of inputs = " & total)
  avg = total / 3
  console.writeline("the average of inputs = " & avg)
end sub

What might be considered wrong about the use of the subroutine above? How could it be fixed?

Answer:

The sub routine is performing multiple function: it calculates the total AND the average. Functions/procedures should only perform one task at a time. You could replace the above with two subroutines:

  • calcAvg(...)
  • calcTotal(...)

List three reasons for using functions and procedures to structure your code

Answer:

  • You can re-use the code
  • You can test parts of the code individually
  • The code is easier to read and understand
dim ppdpdp as string
dim cheesy as integer
console.write("hello, please insert your name: ")
ppdpdp = console.readline()
console.write("hello, please insert your age: ")
cheesy = console.readline
if ppdpdp = "Dave" then
if cheesy = 23
console.write("daisy, daisy...")
else
console.write("I'm sorry dave")
end if
else
console.write("Get off my spaceship")
end if

Give three structured programming techniques that could be used to improve the code above:

Answer:

  • proper use of indentation
  • sensible variables names (why on earth have they used cheesy to store the age, why not use age?)
  • use comments