The Trick Of The Mind - Modular Programming
Written by Mike James   
Tuesday, 05 September 2023
Article Index
The Trick Of The Mind - Modular Programming
Parameters
There Can Be More Than One

There Can Be More Than One

Functions are subroutines that return only a single result – what if you need to return more than one result? The answer depends on how much you value the functional approach to programming. There are two broad approaches. If you want to retain the ability to write expressions then you enforce the restriction to a single result. If you want to be more libertarian you can invent a way to allow subroutines to return multiple results.

This raises some questions. First, how can you live with the one-result rule if you have multiple results? The answer is you can package your results into a single entity and then return it as your “single” result. This is what languages such as Python do. Consider for example a function that works out the maximum and the minimum:

Function MaxMin(a,b)
	If a > b Then
 		  max = a 
		  min = b
	If a <= b Then
 		  max = b 
		  min = a
	Return (max,min)

In this case we are returning two values packaged together as a single entity called a tuple – the name is borrowed from mathematics. A tuple is like a simplified array or list. When you use the function the result returned is a tuple:

result = MaxMin(3,10)

stores the tuple (10,3) in result. Obviously you can’t use a tuple in a standard arithmetic expression, but with the addition of some extra commands you can make tuples useful in the same way. For example, you can invent a notation that gives you each of the values in the tuple as if it was an array or list:

result[0]

is the first value in the tuple and

result[1]

is the second value. Note we start counting from zero because this is the way every programming language does it.

So you could write things like:

range = MaxMin(3,10)[0] – MaxMin(3,10)[1]

to work out the difference between the maximum and the minimum. Clearly, this is not as simple as using a simple function, but it’s not too bad.

Functions can be used to return multiple values as long as the language being used provides a way to package the values into a single entity and provides the necessary instructions to work with that entity.

The alternative is to give up on functions and allow subroutines to return values other than by a return instruction. The most common way to do this is to extend the idea of a parameter to In and Out parameters. Of course, In parameters are what we have simply been calling parameters. An In parameter transfers a value from its argument to the parameter before the subroutine starts. An Out parameter transfers the value of the parameter to the argument when the subroutine ends. For example:

Function MaxMin(In a,In b, Out max, Out min)
	If a > b Then
 		  max = a 
		  min = b
	If a<=b Then
 		  max = b 
		  min = a
	Return

Now we have two In parameters and two Out parameters. The subroutine would be used something like:

MaxMin(3,10,myMax,myMin)

and this would result in myMax being 10 and myMin being 3.

Different programming languages adopt different ways of letting you use In and Out parameters. Some define all parameters as In parameters, others allow you to have InOut parameters by default and so on. However they are implemented and whatever they are called the basic idea is the same.

Today, the most popular approach is to use functions and nothing but functions. For example, Python only has functions and to get multiple values returned you have to use a tuple, or something similar, to package the result. The only downside of this approach is that one-language programmers don’t get to see that there is any other way of doing the job.

Subroutines Have Sub-Subroutines

With apologies to Jonathan Swift:

So, naturalists observe, a flea
Has smaller fleas that on him prey;
And these have smaller still to bite 'em;
And so proceed ad infinitum.

When you find that a subroutine is becoming large and so difficult to understand then it’s a good idea to split it into smaller units i.e. into more subroutines. Our MakeCoffee subroutine might be better implemented as:

Subroutine MakeCoffee(Sugar)
	get cup
	dispense coffee into cup
	Repeat Sugar Times 
		add spoon of sugar
	If Sugar>0 Then stir
	Return

Now we can vary the number of sugars added, but our subroutine is starting to look a little more complicated than before.

We could simplify it by creating an AddSugar subroutine:

Subroutine AddSugar(Number)
	repeat Number Times
add spoon of sugar stir Return

This adds the required number of spoonfuls of sugar and stirs the result. Using this our MakeCoffee subroutine is:

Subroutine MakeCoffee(Sugar)
	get cup
	dispense coffee into cup
	AddSugar(Sugar)

This is much simpler and it is a general example of the rule that the extensive use of subroutines simplifies code.

This is the start of the idea that as much as possible in a program should be converted into subroutines or functions. It is the idea that any small piece of code that does an identifiable job should be given a name and used as if it was a new command in the language. Programs can be made up of nothing but subroutines that call other subroutines, which in turn call other subroutines and so on down to some tiny minority of “drone” subroutines that actually get some work done.

This is another of those great ideas that was soundly rejected when it was first proposed. Programmers in the early days had grown accustomed to writing their programs as one long stream-of-consciousness thought. The initial reason for this was efficiency. Early computers didn’t have the power to waste on implementing calls and returns to subroutines. Put simply, programs that used subroutines were slower. As computer hardware improved, the overheads in using subroutines became irrelevant and the advantages of simplicity became so worthwhile as to be unavoidable.

This conclusion was not something that was clear to programmers brought up on the single-routine program. They claimed that being able to see everything in one place without having to go off and find the text of any subroutines used was simpler and safer. They were, of course, wrong and today programs are almost universally written as collections of subroutines. The convenience of not having to worry about how a subroutine works while examining how the subroutine is used is overwhelming.

Using subroutines in this way leads to an approach to constructing programs that, to this day, hasn’t been improved on. Known as Top Down Structured programming, it is the subject of the next chapter.

Summary

  • Subroutines, procedures, modules and functions are names for the way that we can group instructions together and use them as if they were a new instruction.

  • When a subroutine is called, control passes to its first instruction and when it is finished it returns control to the instruction after the call instruction.

  • By adding a return statement to our collection of instructions we can place the exit of a subroutine at a location other than the end.

  • Using parameters we can pass information into a subroutine to determine what it actually does.

  • Parameters have no relationship to variables of the same name used in the calling program. Subroutines provide a layer of encapsulation which isolates the code you write from the calling program.

  • A subroutine that returns a single value is called a function.

  • Functions can be used within arithmetic expressions to make them Turing-complete.

  • Returning more than a single value is a difficult problem. The usual solution is to allow multiple results to be packaged into a single entity and returned as a single result. Alternatively you can allow Out parameters to return values – out parameters.

  • The best approach to creating programs is to write lots of subroutines and write subroutines that call other subroutines.

The Trick Of The Mind - Programming & ComputationalThought

Buy Now From Amazon

Trick360

Chapter List

  1. The Trick Of The Mind

  2. Little Languages
       Extract: Little Languages Arithmetic

  3. Big Languages Are Turing Complete

  4. The Strange Incident of The Goto Considered Harmful
       Extract: The Goto Considered Harmful

  5. On Being Variable  

  6. Representation

  7. The Loop Zoo
       Extract The Loop Zoo
      
    Extract Advanced Loops

  8. Modules, Subroutines, Procedures and Functions
       Extract Modular Programming

  9. Top-Down Programming 

  10. Algorithms
       Extract: Binary Search 
       Extract: Recursion ***NEW!!

  11. The Scientific Method As Debugging 

  12. The Object Of It All
       Extract Why Objects 

 <ASIN:1871962722>

<ASIN:B09MDL5J1S>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


SQL Turns 50
10/06/2024

The first release of SQL was in June 1974. Designed at IBM by Donald D. Chamberlin and Raymond F. Boyce, it was based on the relational model proposed by E.F. Codd. SQL became the most widely used dat [ ... ]



GitHub Actions Adds Arm-Hosted Runners
06/06/2024

GitHub has added Arm-based Linux and Windows runners for GitHub Actions. The developers say the addition provides power, performance and sustainability improvements for all your GitHub Actions jobs.


More News

C book

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Saturday, 04 November 2023 )