Do one thing, and do it well
In our first installment, we wrote several programs that really did nothing more than illustrate a concept. Let’s turn the complexity up a notch and compose a program that actually solves a problem. The problem we are tasked with: given the high temperature of the past three days, compute the average and standard deviation.
To do this, we are going to need to implement an algorithm, the programming equivalent to a set of directions. It gives the major steps that one must take in order to solve a problem, but the details of how are left up to the programmer who implements the algorithm. For our problem at hand, we could write out our algorithm as follows:
- Read in three values
- Compute the sum of these values
- Compute the average by dividing the sum by 3.
- Figure out how far each value is from the average.
- Add the square of the distances obtained in step four
- Take the square root of the value in step five
- Divide by the square root of 3
So, let us set out to implement our remedial algorithm in MHF:
PROGRAM weatherStation
NUMBER temperature1 # tell the computer that we're going to need
NUMBER temperature2 # space set aside for the three temperatures
NUMBER temperature3 # plus space for the average and standard
NUMBER averageTemp # deviation results
NUMBER stddevTemp
NUMBER sum, sqDist1, sqDist2, sqDist3 # we can define multiple
# variables of the same type
# on one line
READ temperature1 # interface with someone or something
READ temperature2 # to get our three temperature readings
READ temperature3 # algorithm step 1
# algorithm step 2
sum = temperature1 + temperature2 + temperature3
# algorithm step 3
averageTemp = sum / 3.0
# steps 4 and half of 5 from the algorithm
sqDist1 = (temperature1 - averageTemp)^2
sqDist2 = (temperature2 - averageTemp)^2
sqDist3 = (temperature3 - averageTemp)^2
# other half of 5 and step 6 from the algorithm
stddevTemp = ((sqDist1+sqDist2+sqDist3)/3.0)^(0.5)
PRINT "Average temperature = ", averageTemp, "+/-", stddevTemp
END PROGRAM weatherStation
The weatherStation program follows the algorithm laid out above and calculates the average and the standard deviation of three temperature readings. But it’s not possible to directly map the steps of the algorithm to the code. Some steps are split over multiple lines; other lines do more than a single step.
This example is reminiscent of real world development—as programs grow in complexity and size, it can be harder to track what individual steps are meant to accomplish.
To make the code easier to follow, and to allow the same operation to be done at multiple locations in the code, it’s often useful to compartmentalize your code. All major programming languages (that I am aware of) support what are called functions, methods, or subroutines. These allow programmers to pull out related operations and place them in their own module, where they are separated from other parts of the program.

Loading comments...