Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

DarkBASIC Discussion / DNG - Program Structure & Flow

Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 3rd Aug 2010 01:52 Edited at: 1st Apr 2012 22:38
Program Structure: A Brief Guide to Writing Better Code

Preface: Rise of the Spaghetti Monster!
When first learning to write computer programs it's natural to start at the top and work your way down. This format is easy to follow but in most cases involves repeatedly typing much of the same code. When you learn the goto command it appears to solve all your problems. Now instead of duplicating code you can jump to the same passage again and again, what fun! The fun is brought to an abrupt and cruel end, however, with the first error message; there's no way of trekking through the jumbled jungle of jumps; there's no trace of tracks to follow back; you are lost, forever trapped in the twisted clutches of the dreaded spaghetti monster!

This brief guide aims to help emerging coders refine their style to produce more efficient code that's easier to read, write, debug and implement. This is of particular importantance when working in teams as your code must be understood by your team mates and compatible with their code.
I have been a member of the Dark Basic forums for a number of years and almost all principles outlined here I learned from other coders on those forums. I say this not only in modesty to those coders of far greater experience and skill than myself, but in the hope that you too will seek out good practices from your fellow programmers and claim them as your own. Reading and modifying an impressive program is one of the best, and fun, ways to learn.

Before you begin writing any actual code, it's often helpful to lay out a vague structure for your program, this is called the program skeleton. The program skeleton can be split into three sections: head, body and routines (or entrails for those wanting to keep this anatomical metaphor alive); as we write our program we'll flesh out each section in greater detail. The head of the skeleton is the program header, we flesh out the head by adding a comment block containing the program title, author, date, the names of any contributors or important sources and any other important information about the project. As well as giving our skeleton a sense of identity, his head can also be filled with things like declaring variables, constants, arrays and calls to load media -- basically all the things we need to start the program off.

The body of the program is often referred to as the main loop because most of the time we want our programs to reiterate until the user gets bored, when this inevitability occurs it's only polite to allow the user to leave without resorting to man-on-machine violence. To this end it's better to avoid using infinite loops (do-loop, for example) and instead use conditional loops (e.g. repeat-until), but this is not obligatory and as long as you give the user a way out they wont know the difference. The main loop contains all the program code, but as your program advances you'll find it beneficial to evacuate common passages to independent subroutines or functions. In this advanced program structure the main loop can be viewed as the heart of the program, pumping the program flow around all the vital organs (subroutines and functions).

Now we come to the third and final part of our skeleton: the entrails, but if you use that term in public people will smile and back away from you so let's stick to subroutines and functions. Unless you have brilliant planning skills, you wont realize which bits of code could work as subroutines or functions until you write them, so keep an eye out for patterns in your code that could be condensed into a single routine or function -- while doing this you should also look for ways to simplify your code and make it even better. Some of you might not have heard of functions or subroutines before, or don't yet appreciate their value.
Subroutines, or subs for short, are blocks of code that perform one distinct task. A subroutine can be called many times and at any point in the program. As a pleasant side-effect, subroutines shrink your program and make it easier to read by replacing blocks of code with self-explanatory calls, providing you give them descriptive names.
Functions are similar to subroutines in that they extract a common task from the main loop for use as and when required. The difference is functions are more flexible: pass them any parameters (of the correct type) and they'll work with them, which means you can use functions not only on multiple occasions but in altogether different situations. Functions inhabit their own scope, which means they are blind to all other variables in the program except those which are passed to them as parameters or have been declared global. This independent scope is very useful for compatability with other programs because variables used in functions never conflict with those outside the function: even if they have identical names they are seen as different variables. For this reason functions are great for team projects and common routines you'll need many times over.
To help visualize the effect subroutines and functions have on your programs, I've drawn a diagram.

Using subroutines and functions can be thought of as adding dimensions to your code. A basic stream of code can be viewed as a single line flowing from left to right. (Using lots of gotos to jump about would cause the line to bend and weave, overlapping itself, hence the term "spaghetti code".) Subroutines add a second dimension to your code: your main code line is running left to right as before, but now we have subroutines running parrelel to it available to be called at any time -- the lines of different lengths are calls to different subroutines. Functions add the third dimension. (I labelled it incorrectly! The function calls should be along the bottom face of the cube with the parameters rising out of them.) Here we have not only calls of different lengths, representing different functions, but many possible parameters for each function. It's clear to see the possibilities and flexibility opened up by using subroutines and functions.

Miscellaneous Tips

Indent your code to show where one command ends and another begins. When commands span multiple lines, indent the contents between the opening and closing statements. Indentation can be nested in many levels but must remain clear and consistent, like so:

Plan your programs before coding, you can often solve many issues ahead of time and avoid wasting effort writing redundant code. Using a program skeleton is a basic form of planning but you can also write down your ideas and develop them to explore any issues that might occur, writing pseudo code is often helpful, for example:

These titles may even become the names of your subroutines.
Format your code in a clear and consistent manner. Use symbols, capital letters and whitespace to clearly define different sections, like so:

Join DNG today! We are a game development team open to all. Visit our Headquarters to learn more.

Login to post a reply

Server time is: 2020-08-12 00:54:56
Your offset time is: 2020-08-12 00:54:56