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 / Tutorial: How To Write Well Presented And Efficient Code (Second Edition)

Author
Message
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 10th Oct 2008 06:06 Edited at: 24th Aug 2010 23:19
I have heavily revised this reference, it is still a work in progress but I think it is at the stage where it'll be of use to people.

________________________________________________________


How To Write Well Presented And Efficient Code (Second Edition)

Quote: "TDK: A main program loop with 200 lines of code and no procedures is untidy, hard to read and shows lack of programming experience."

TDK's Tutorials

It is all well and good being able to write a program that "works"; it is another thing to write a program that can be read, understood and if need be, ammended.
In this tutorial I will provide you with methods to achieve this goal.

Before beginning it is worth bearing in mind that there is no "right" way to structure your code; code structure encompasses everything you do as a programmer and so there are as many methods as commands themselves.

It is also worth mentioning that this is a tutorial exclusively about structure, if you have any questions about how to use commands this is not the place; there are many tutorials that cover commands: such as TDK's http://forum.thegamecreators.com/?m=forum_view&t=99497&b=10

Contents
Topic 1: Layout
Topic 2: Documentation
Topic 3: Planning
Topic 4: Economy

Please post your comments in this thread. Any suggestions or corrections will only help to improve this tutorial.
Thanks,

OBese87


________________________________________________________


TOPIC 1: Layout
Groups
Before we can write structured code, we obviously need a structure.
We can create an organised structure by grouping statements that perform similar tasks.
Grouping subroutines and functions below the main loop keeps them tidy and out of the way.
Always place subroutines before functions; if you declare an array in a subroutine it must come before the function that uses it or the program will crash.

Grouping on a smaller scale further improves the readability of your code.
By grouping similar commands it becomes easier to follow the flow of your code.
e.g.


The Main Loop
The main loop is the hub of a program; it points to all the subroutines and functions that are required to keep the program running.
Try to write it as a conditional loop - when the conditions are met to leave the main loop the program should also end - this enables you to end the program in a much classier way than a do-loop, which forces the user to press F12 before they are allowed to leave.
By definition the main loop should be relatively short consisting mainly of calls rather than actual commands.

Indentation
When a command consumes more than one line, indent the code within the opening and closing statements so that you can clearly see where each command begins and ends. This is of great importance if you ever want help from other coders in the forums :-p.

Here's an example without indentation:


and the same code indented:

There is a vast difference between the two; the latter is much easier to follow.

TOPIC 2: Documentation
Even if your program has a good layout it can still be difficult to see what it does straight away.
Remarks are brief notes you can add to your code to help make it easier to understand, this not only helps others but can also refresh your own memory when you come back to an old program or work in progress.

Here is an example without documentation:

All we can determine from this is that the two-dimensional array "win" has been created, and five values assigned.

and the documented version of the same code:

Now we can clearly see what the array is for, and what each field does.

Headings and Auxiliary Remarks
In the above code, I used two types of remark:
A header remark

and several auxiliary remarks

Auxiliary remarks are very useful as they allow us to document our code and still save lines. However, they can only document a single line of code, so to explain an entire block of code we use a header remark.

Boundaries
You can use symbols in remarks to give your program distinct boundaries. Coming up with your own system of boundaries can help you quickly navigate your code.
Here's an example of the type of boundaries I use.


TOPIC 3: Planning
No-one can write a perfect program in one fell swoop, we'd need some sort of amazing self-programming machine to do that, and the mad programmer who takes on the task will have to plan his code very carefully indeed!
I think of planning in the same way as sketching a portrait; if you start off by drawing the basic shapes, filling in the details later, you'll come away with something quite life-like. If you dive straight in and draw the entire thing without lifting your pencil you're just going to offend people.

Gosub Skeletons
Revisiting our sketch metaphor for a moment: the gosub skeleton is the basic shapes of our portrait; all we are doing is listing the routines that our program will require, we'll fill in the actual code later.

Every gosub should always return to the main loop.

The great benefit of using gosubs in this way is that it makes our program very easy to follow: we can just read the processes our program is going through without having to look through every single line of code and work it out. Another benefit is that while we are in the development phase, we can switch our gosubs on/off (by remming them out) when we want; this is extremely helpful for isolating bugs.

Testing & De-Bugging
Even experienced programmers make mistakes, and the mistakes that waste the most time tend to be simple errors like typos. The difficulty in fixing a bug is finding the cause, especially if you have a large program.

The most basic method of de-bugging is via process of elimination, as Sherlock Holmes said:
"When you eliminate the impossible, then whatever is left, no matter how improbable, must be the truth."
If we find everything that works, whatever is left must be what doesn't work.
Let's get to it! Since we are good programmers and we have planned out our program into subroutines, this should be easy.

When we rem out the "format_font" gosub our program works fine, it's only when we include it that DB mocks us with its error messages. So that's where our problem is!
Now we could go through the process of remming out each line and narrowing down the problem until we find the exact line that is causing trouble, but since this is a simple syntax error it is quite easy to spot: we have been trying to set the text "funt", I'm not sure what setting the funt does but it's not what we wanted to do. We change "funt" to "font", strip all the rems out of our code and hey-presto, it works! (You cannot set text funt)

All that remming out lines may be quick and painless for smaller programs but with larger ones it is worth writing a small "bug trap" to make DB show you what is going wrong. Most of the time bugs slip past you because the outcome of the offending procedure is not displayed on screen, so... we display it on screen!
This example is based on a DB Challenge entry that I wrote; it is designed to sort the animal names into alphabetical order:

Copy this program into your editor and run it. You'll see that something has gone wrong. The lion seems to have bred another 3 lions and they've eaten the zebra, the tiger and the rhino! To find out what is happening, I've written a "bug trap" that will print the position of each animal in the sort array as the animals are sorted.


Here is the program again with the new bug trap slotted in. Please copy this into your editor and run it.


We can now see that the animal names are not being shifted properly; the higher entries are overwriting the lower ones!
Here's the code with the bug fixed:

Now all the animals are being shifted around properly and are displaying in alphabetical order.

Compatibility
Sooner or later you are going to write a program that you are so proud of you want to share it with the DB community.
How horrible would it be if your moment of shining glory was tarnished by people saying your code didn't work?
The problem is that what works fine on your computer wont necessarily work on other peoples'. Luckily DB lets you standardise the way your programs run. [unfinished]

TOPIC 4: Economy
"It's the economy stupid!" - Ah if only this was a tutorial where each topic had a not-so-witty quote that was very loosely tied to it's subject matter.

Economy serves two masters - the computer and the author - but these masters have a conflict of interests.
When economy reduces the workload of the program by executing every command only when it is absolutely neccessary it serves the computer; when it reduces or modulates the code into independent procedures that are easier to manage and utilise it serves the author.
Economy tends to tip towards the computer when writing very demanding programs but on the whole it is much more beneficial to economise for the author. [unfinished]

Using The Right Commands

Program Speed

Sinani201
17
Years of Service
User Offline
Joined: 16th Apr 2007
Location: Aperture Science Enrichment Center
Posted: 10th Oct 2008 18:34
*Gasp* A SECOND one? No way!

I haven't read all of it, but it looks good. However, when I make attempts to make games, I normally use the Pac-Man tutorial for my structure...


"I reveal my trap card, GEORGE DUBYA BUSH!
America loses 2000 Life Points! America loses." -Deucalion2
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 12th Oct 2008 23:41 Edited at: 12th Oct 2008 23:42
Quote: "*Gasp* A SECOND one? No way!"

It's just an edited version of the first one but that was auto-locked.

Thanks for the compliment
where is the pacman tutorial maybe it has some good tips I can add here?

A small program that works is better than a large one that doesn't.

DBC Challenge Rank: Rookie
Sinani201
17
Years of Service
User Offline
Joined: 16th Apr 2007
Location: Aperture Science Enrichment Center
Posted: 13th Oct 2008 00:02 Edited at: 13th Oct 2008 00:03
It's on the DBPro forum. Let me dig a up the link...

[EDIT] It is here.


"I reveal my trap card, GEORGE DUBYA BUSH!
America loses 2000 Life Points! America loses." -Deucalion2
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 13th Oct 2008 00:42
That is an awesome tutorial it's basically everything you need to know to make a game!
There's quite a bit on planning so maybe there's some stuff I can fish out of it.

A small program that works is better than a large one that doesn't.

DBC Challenge Rank: Rookie
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 14th Nov 2008 20:26
hmm... this has fallen off the top page again.
Is this helpful or do you guys think I need to learn more myself before writing a tutorial?
Or is it just the fact I haven't completed it yet?

A small program that works is better than a large one that doesn't.

DBC Challenge Rank: Rookie
BN2 Productions
20
Years of Service
User Offline
Joined: 22nd Jan 2004
Location:
Posted: 14th Nov 2008 20:38
Wow, I forgot about this one. Was going to read it and then got caught up in the DarkNOOBS project. Very good tutorial.

Quote: "How horrible would it be if your moment of shining glory was tarnished by people saying your code didn't work?"


Very...very....horrible. See my entry to the darkbasic challenge for the furious file scanner. It was mostly a vista to everything else compatability problem, but it took about 10 revisions and finally re-writing some code I got on the codebase to make it work.

But yes, very good tutorial, looking forward to seeing it finished!

Ever notice how in Microsoft word, the word "microsoft" is auto corrected to be "Microsoft" but "macintosh" just gets the dumb red underline?
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 15th Nov 2008 00:14
@BN2
Thanks

Quote: "See my entry to the darkbasic challenge for the furious file scanner. It was mostly a vista to everything else compatability problem, but it took about 10 revisions and finally re-writing some code I got on the codebase to make it work."

What was the problem? Vista seems to be throwing a few curve balls, is it a certain command that messes things up? I need to learn a bit more about compatibility before I can finish that section. The only thing I've ever had to do was set the sync rate and character set.

A small program that works is better than a large one that doesn't.

DBC Challenge Rank: Rookie
BN2 Productions
20
Years of Service
User Offline
Joined: 22nd Jan 2004
Location:
Posted: 15th Nov 2008 01:49
It had to do with the registry. I was trying to read the location of the desktop from the registry, but without memblocks the only way I had been able to do it was to export the registry location to a file then load it and read the location.

For some reason it would create a severe exception whenever I would do it. I don't remember exactly what the problem was, I think it was a mixture of problematic code and vista permission problems. It was a while ago, though, so I don't remember the exact problem.

Ever notice how in Microsoft word, the word "microsoft" is auto corrected to be "Microsoft" but "macintosh" just gets the dumb red underline?
steve paul thomas
15
Years of Service
User Offline
Joined: 4th Nov 2008
Location: United Kingdom
Posted: 15th Nov 2008 05:50 Edited at: 15th Nov 2008 06:04
@OBese87

Great advice Thanks to you and Latch I am now making the effort to properly indent my code (rather than just indenting the first level). Thank you for your tutorial
Ashingda 27
16
Years of Service
User Offline
Joined: 15th Feb 2008
Location:
Posted: 15th Nov 2008 07:16
@Obese

I'm starting to us the

alot and I find it very useful.

Although I prefer REM over ` cause for me it just looks nicer

Thanks for bringing this up.
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 29th Nov 2008 02:59 Edited at: 29th Nov 2008 02:59
Wow I have feedback... and it's good!
Thanks BN2, Ashingda and Steve.

I haven't responded to any pointers yet so here it is...
@Windowskiller
Quote: "Just a note on that. Professional programmers normally don't add comments that tell what the code does, but WHY it does what it does. E.g. when setting up global variables, add a comment why they must be global, not something like "ยด set up globals", as you can see that from the code anyway.

I have to admit that I don't follow that rule either, but basically, descriptive comments are useless and just bloat the code. And if you need to add comments to describe your variables, then you should rather think again about the variables' names. They should be self-explaining."

Some good points there, I had trouble thinking of a situation that would need a "why" and that window array is an awful example - like you said: having to explain the name means it's a bad name!
It should really be separate arrays for window_x and window_y etc.
so no explanation of individual fields is needed. This is a habit I've luckily grown out of though.

A small program that works is better than a large one that doesn't.

DBC Challenge Rank: Rookie

Login to post a reply

Server time is: 2024-05-01 11:33:20
Your offset time is: 2024-05-01 11:33:20