LitDev strikes again with another fantastic article on TechNet Wiki:
This article covers the basic ideas of structured programming, or some tips for writing better programs in Small Basic.
Subroutines are pieces of code that perform a specific task. Often the task may be needed in different parts of your code and prevent duplication of code. If you are writing very similar code for different parts of your program, then probably subroutines could help.
A subroutine in Small Basic starts with the keyword Sub and ends with EndSub. It can then be called by using the subroutine name followed by two round braces ().
- value = Math.Pi
- Sub roundResult
- result = 0.001*(Math.Floor(1000*value+0.5))
- Sub writeOutput
- TextWindow.WriteLine(“the current value rounded to 3 decimals is “+result)
The subroutine code block can be placed anywhere in your code, but it is best to place them all together after you main code.
Often we can break a task into a number of sub tasks, each of which could then be a subroutine.
The length of a subroutine is not that important, don’t just subdivide a long piece of code into subroutines unless each has a specific task. Generally it is good if the main or top-level subroutines are quite short so it is easy to follow the main logic of the program.
The key to subroutines is:
- Making them do just one task – it may be very general like “Initialise Program” and include many sub tasks or be very specific like “Check overlap of 2 shapes”. You should be able to describe the subroutine task in just a few words and don’t tempted to ‘just add in a little something else’.
- Make them as general as possible – especially if you might want to reuse the code in other programs. See the section on “Variables or constants”.