'Better' is subjective and people do prefer different styles, but there are some general rules that do help, especially when your programs get more complicated.
This is the most controversial and opinion differs.
Normally a program runs one line, then the next, progressing through the code in a logical order. It can do For or While loops and branch into different code using If, ElseIf and EndIf. The path taken through the code is sometimes called the 'flow' of the code. We want this flow to be as clear and logical as possible.
A GoTo just jumps somewhere completely different. This can make the code very hard to follow and virtually impossible to debug or extend if they are used indiscriminately. However, they are a very natural concept for the starting programmer before they know much about other ways to control the flow of code.
Below is a sample code using GoTo's too much - what is it supposed to do and why doesn't it work?
x
=
0
y
For
i
1
To
100
a
:
+
b
-
c
If
(
<
10
)
Then
Goto
Else
EndIf
3
EndFor
TextWindow
.
WriteLine
" "
This example works fine, but is still very hard to follow.
start
clear
Pause
Clear
Start
count
enterNumber
"Enter a number"
num1
ReadNumber
ElseIf
2
num2
getOperation
"Enter an operation (+,-,*,/)"
operation
Textwindow
Read
>
"+"
And
"-"
"*"
"/"
dosum
result
"="
/
*
These are called 'spaghetti' code.
The general rule is for every GoTo that you use, you should consider very carefully if there is a better way to do it - there almost always is. There are occasions in Small Basic where it is the best option, but they are very rare.
You should never use a GoTo to jump into or out from a subroutine or your program will crash. This is because the call stack will be corrupted. The call stack is an internal structure that controls where a subroutine should return to when it ends and is updated when the subroutine is called and returned from.
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
roundResult
writeOutput
Sub
0.001
Floor
1000
0.5
EndSub
"the current value rounded to 3 decimals is "
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:
A comment in Small Basic starts with an apostrophe ' and is highlighted in green. Anything after it is ignored to the end of the line.
'Calculate distance between objects
distance
SquareRoot
'(x,y) is the player
Comments are not just for others reading your code, they help remind you later why you did something. More importantly they show the thinking behind the code and the ideas about how the program should work.
Try to add comments that explain something complex or why you did something one way or another. They should remind you and help someone else understand the overall thinking you had when you wrote the program.
The 'more comments the better' is not good, the following comment adds nothing.
5
'Add 5 to x
Sometimes comments can be used to visually separate sections of your code like the start of subroutines.
'===================================================
'SUBROUTINES
Try to use descriptive names for your variables, there is no penalty in performance or memory for long variable names. Try not to make them too long, but be clear what they are.
There are conventions for variable naming, but most common is to mainly use lower case and capitalise each word apart from the first (that remains lower case).
For loop counters are usually just a single character, i, j, k etc.
playerTank
Shapes
AddImage
playerTankImage
numEnemy
enemyTank
[
]
enemyTankImage
Sometimes in your code you use a value that is fixed, perhaps the number of enemies, or offset for positioning a shape at its centre or the text used to ask a question.
It is good practice to put all these constants in variables so that you can just change the variable without having to change the constant values throughout your code. It can also make your code more general so that it can be re-used or subroutines used more extensively, reducing the need for duplicate code. All the variables can be simply initialised in one subroutine at the start.
GraphicsWindow
Show
displayText
"Hello World"
11
letter
Text
GetSubText
,
letterShape
AddText
j
Move
20
Program
Delay
100)
The code above would be better written as below so we can easily change the parameters of the method if we change the font for example.
Initialise
howText
characterOffset
movingLetterSteps
delayMovingLetter
delayLetter
ShowText
GetLength
Use arrays where possible to group items. For example if you have multiple buttons, put them all in an array. In the example below all we need to do to add more buttons is add a new buttonText array element.
Controls
ButtonClicked
OnButtonClicked
buttonText
"Clear"
"Start"
"Run"
4
"Pause"
"Exit"
numButton
Array
GetItemCount
button
AddButton
60
50
Height
40
SetSize
30
'Equal size to look better
lastButton
LastClickedButton
ShowMessage
" was clicked"
"Information"
Use the indentation feature of Small Basic to format your code. This can be found by right clicking and select 'Format Program'.
Also use blank lines to separate code segments, but try not to have lots of randomly placed blank lines.
Place your main code at the start, then place all subroutines below the main code, perhaps separating program subroutines and event subroutines.
Perhaps also separate your main code into sections like 'Initialisation and Setup', 'Main Program' or others that may apply.
Try to think of a program structure at the start, then create the main subroutines and variables/arrays and gradually add the detail. Test detail in small prototype programs first, then add to the main program.
The temptation is to add all the fine detail of a program at the start and then build a structure around this, but this will often lead to code that is hard to develop and debug.
Richard Mueller edited Revision 5. Comment: Replaced RGB values with color names in HTML to restore colors
Richard Mueller edited Revision 4. Comment: Added tags
litdev edited Revision 2. Comment: typos
litdev edited Revision 1. Comment: typos
Great tips. Not too complicated. A big help to me. This language is all for kids and beginners and that's exactly who the above article caters for.
I work as a cook and i'm planning on doing a course this year on programming (hopefully i can fit it in) and i've always wanted to program becuase i just love to be able to tell the computer how to do something that i want it to do. Very satisfying.
Useful for clss room. Thanks
Useful for class room. Thanks
Have just been working through the Events & Interactivity section of the curriculum and realised something that could be useful to your article.
If the program has Interactivity then:
As part of the planning process, probably the first step, design the GUI. Setting out the GUI first can also help clarify the program flow.This is best done by first fully setting it out on a piece of scratch paper or a drawing application. Be mindful of Basic design principles en.wikipedia.org/.../Design_elements_and_principles. Also using these design principles allow for expansion of the GUI, e.g. perhaps near an Exit button you might want to leave a bit of space to add a Back button latter then maybe latter on a Next button.
Once you have set out the GUI and are satisfied it's complete with some room for expansion. Code it as a Subroutine called InitGUI. You may have more than one GUI, then you could call each Subroutine InitWelcomeGUI, InitPersonalFormGUI, InitHelpGUI etc.
Hey LitDev i like this article. I think it has much potential to grow. My above comment may be a bit too detailed for first glance beginners but it could be delt with as a "More Details" link.
Also if it's ok with you i'd like to offer the occassional contribution to your article as I learn more about programming. What would be the best way to do this? Should i do it by using the Edit Tab at the top as i think Proposed Contributions are not best placed as comments.
Regards
Great article. Very useful. Thank you.