You are visitor number
Nico's Introduction to the Art of Computer Programming
This is for VB Java and Delphi programmers
This is the property of Nico Michael . This information is my original work and may not be reproduced without my prior consent.
One of the problems today is that some VB Programmers are lazy and dive straight
into the keyboard to start developing code that requires hours/days of debugging to get it
work satisfactorily. And NO PROGRAMMERS COMMENTS making fault finding an extremely tedious
operation
The Comments explain how the components fit together , the purpose of the Functions and
Variables.
Choose your Variable and Procedure names carefully use the Hungarian Naming
convention it helps prevent type mismatches in your code and helps others to figure out
what you are trying to do.
I also noticed that the VB training courses concentrate on the User Interface and neglect to teach the novice programmer the basics and even techniques which can be used to develop more advanced and complex code.They assume that the Novice will acquire the knowledge of the Language and programming techniques later. But why not teach the Novice the techniques
Developing software for large corporations requires programming to meet high standards and to be able to work in teams to develop larger applications. Your code must me reliable.
Avoid writing excessively complex procedures which will invariably have
hidden bugs
A well written program is one that has been planned very carefully and has enough
programmers comments to make it easy for maintenance. If your procedures become
complex its time to re-visit your flowchart and spend some time
simplifying it.
Don't write Spaghetti code. I remember spending hours trying to figure out how a
program worked because the programmer did not plan the code and used thousands of GOTO
commands. I wish they would send the person who invented the GOTO Command to Firing Squad
. I dedicated a section to Structured Programming to teach Novices not to use the GOTO
Careful use of the IF Else Endif structure achieves the same thing without the Spaghetti.
The only goto you could use is the
ON ERROR GOTO error trap code.
Every Hour spent optimizing your design on paper (flowchart) results in a day saved
debugging your code.
What the heck is version control who the heck needs to keep track of changes I
know what I am doing anyway.
2 Writing User Friendly
Applications
This is an example of an untidy and complicated screen
This is an example of a Neat and logical screen
You may ask what is an Algorithm and what is Pseudo Code.
An Algorithm is like a Recipe it gives the programmer instructions how to
write the program
Pseudo Code is an almost computer language with interactions for
the programmer write the program.
Well lets try to explain its like this :
You write a few English Commands / instructions on a piece of paper to describe
what you want the program to do.
Pseudo code is also useful for describing to a non-programmer what you want to do
in a way that will assist that person to understand what you want to do
Remember you are not writing a program but describing the tasks or process you need to make your program
Practical Example:
1 DISPLAY MESSAGE TO PROMPT USER FOR INPUT
2 GET INPUT FROM USER
3 GET THE FIRST CHARACTER
4 REPEAT THE FOLLOWING PROCESS UNTIL ALL LETTERS HAVE BEEN CONVERTED
5 CONVERT CHARACTER TO NUMBER (ASCII VALUE)
6 IS NUMBER GREATER THAN ASCII LOWER CASE c LESS ONE
7 IF TRUE DEDUCT DIFFERENCE THEN
8 DEDUCT DIFFERENCE BETWEEN ACSII LOWER CASE AND ASCII UPPERCASE A FROM NUMBER
9 CONVERT NUMBER BACK TO A CHARACTER
Other Examples for you to try out
Write an Algorithm for a Video Recorder
Write an Algorithm for a Tea & Coffee Vending machine
Write an Algorithm for a Banking Auto Teller
A flow chart is a simple diagram that is used to show the flow
through a program.
It is the most valuable tool for designing and optimizing programs.
A flow chart is the universally accepted representation for describing programs
The are many components however the following are the most commonly used :
1 The Begin and End terminals
2 Process boxes
3 The Decision
5 The need to Document your Design and Source Code (inline comments)
Why bother to document your code it waists time. Besides I know how the program works so I don't need to tell myself how to fix it. I am a brilliant programmer and never forget any line of code I have written. I don't like working in a team and I don't want to share my knowledge or skills. I write my code as complicated as I can so that my colleagues will admire my talent.
If this has not convinced you try this
I spend 5 to 10 minutes to figure out what I did a year ago and if I did not
have my comments it would take me longer
In order for me to work on new and more interesting projects I need to hand over my code
to someone else to maintain I don't want my colleague to battle nor do I want my
colleagues to have a bad impression about my software projects so I put in the effort to
document the code.
Have you considered that one day you will develop code that your employer may want to sell
to the customer. Your employer will be criticized for your workmanship if it is
defective
To guarantee a high standard of quality the larger companies subscribe to Quality
Control standards Internationally recognized such as ISO9001 which makes it mandatory to
have document control and even version control
So start getting used to this idea now and it will become second nature to you
6 Planning your Application (Code , GUI screens, writing Stubs & Drivers)
Every hour spent planning results in a day saved debugging.So put in the effort and you will be rewarded you way also gain a reputation of being the programmer who's code has the least problems
You must plan your application design the GUI interfaces on paper . Draw
flowcharts for the more complex procedures
Plan the testing of your application. Decide what you want to test and how you want to test and save your test results it will be mandatory when your employer implies the ISO9001Quality Standard
Write drivers to call your procedures and stubs which terminate your procedures
The Driver is a procedure that will call you procedure passing it values
The stub is a procedure your procedure will call and the values passed to
your procedure and the variables returned
By monitoring the values passed to you procedure and values returned you test
Test your application with bad data not only good data after all you are trying to find bugs not to prove that it works with good data.
Plan Changes
Plan Changes that you have to introduce to keep the customer satisfied.
Never dive into a working application and make "Quick Changes" you
will spend hours or days trying to fix them
Professional Companies always have a backout plan to cater for failed changes.
Failed changes are more likely to occur because of a lack of planning
Variables are storage places in the computers memory.
Variables are given Names so that it is easier to use and to manage
There are a few basic types of variables : Numbers Text and Date/Time
Numbers are Integer (Numbers with no decimals) or Real
(Floating point numbers numbers with decimals and even exponents)
Text is referred as String variables
Date /Time variables store Date and time and are used for Date
Arithmetic
Combination of the above known as Variant variables
You get Single Cell variables and Multi-Cell variables known as Multi- Dimensional Arrays
From the above all High Level Languages derive their variable however the size of variable is also taken into account
Variable Type | Description |
Integer | Stores numbers with no decimals |
Long | Stores Larger Integers |
Single | Stores (Floating point) Numbers with decimals (Scientific format) |
Double | Stores Larger Singles |
Byte | An 8 Bit number 0 to 255 or a character |
Boolean | A Yes /No type variable stores "True" or "False" |
Currency | Stores Numbers with Decimals |
String | Stores text |
Date | Stores date and time values |
Variant | This is a variable that can
hold any of the above However this take up a large amount of memory |
Object | This is used to make an instance of a class (OOP) |
Naming Variables
When declaring variables observe the following rules
Different programmers have different styles in declaring Variable names
Array Variables Arrays are variables that can simultaneously hold more that one value to text string.Declaring Arrays
Although this is language specific they all have similarities
Dim MemberNames(24) as string This will alloy you to save 25 names or strings in this array
Dim Results(33) as integer This will alloy you to store 34 numbers in this array
Array Indexs
If you wish to store the 15th name in the above array you need to specify the specific array element to save the data this is how its done
MembersNames(14)="Nick Michael"
And if you wish to recall the 19th name this is how you access the specific array element
MsgBox MembersNames(18)
8 Getting Data Input from the User (InputBox)
All High Level Languages have a command for fetching input from the user
When writing windows applications you can use the textbox and InputBox
InputBox is used to Place a small Form on the screen Displaying a message (Prompt) and has a text field for the user to type some input . This will also be waiting for the user to press an OK or Cancel Button before the program continues
VB Code
Private Sub Form_Load()
a = InputBox("What in your Name")
End Sub
9 Displaying Data to the User (MessageBox)
All High Level Languages have a command for writing on the display
When writing windows applications you can use the textbox Listbox and MessageBox
MsgBox is used to Place a small Form on the screen Displaying a message and waiting for the user to press an OK Button before the program continuesVB Code
Private Sub Form_Load()
MsgBox "Hello " & a
End Sub
10 Program Flow Control (Structured Programming)
Example of well structured program
if N=x then
if V=t then
Sub1
else
Sub2
endif
else
if j=k then
sub3
else
sub4
endif
endif
Example of spaghetti
75: goto 100
80: if k>4 goto 110
90: goto 75
100: goto 200
110: if x=3 goto75
200: goto300
220: if j=6 goto 90
300: goto 27 'This reminds me of the story of the Gordon Knot
Alexander the Great once said "What no man can loosen I cut" there for you will never find the goto statement in my programming
If they could put the Man who invented the Goto statement infront of a firing
squad I would volunteer to shoot him.
It is the only statement that can spoil a good program.
1 IF ELSE END IF
A simple English like statement to switch flow between one ore two statements
If Name="John" then
Statement1
Else
Statement2
Endif
2 CASE STATEMENT
A simple English like statement to switch flow to one of many statements
Select Case MembersName
Case "Fred"
Statement1
Case "John"
Statement2
Case Else
Statement 3
End Select
3 FOR NEXT
A simple English like statement to force a block of code to be repeated a fixed number of times
For I= 1 to 10 Step 5
Statement1
Next I
This is the most versatile loop technique as you can specify the lower the upper bound and the increment size (positive or negative)
4 DO WHILE
A simple English like statement to force a block of code to be repeated until a test condition is met
Do
Statement1
While I<5
5 DO UNTIL LOOP
A simple English like statement to force a block of code to be repeated until a test condition is met
Do Until I=10
Statement1
Loop
6 WHILE WEND
A simple English like statement to force a block of code to be repeated until a test condition is met
While I <5
Statement1
Wend
11 Common Language Built-in Functions
Mathematical Functions
Sqr | Square Root |
Log(n) | Natural Log ( log base e) |
Log10(n) | Log10(n) (log base 10) = Log(n) / Log(10) |
Exp | Returns exponent of e
(e=2.718282.) Const e = 2.718281828459 |
Abs | Returns a Positive value for an expression or variable |
Sgn | Returns the sign For Greater than zero returns 1 For Equal to zero returns 0 For Less than zero returns -1 |
Int | Returns an integer (no decimals) |
Trigonometric functions
Sin(x) | Sine of x(radians) |
Sin x in Degrees | Sine of x(degrees)=Sin(x * Rad) |
Cos | Cosine of x(radians) |
Tan | Tanjent of x(radians) |
Atn | Inverse Tangent (arc tan) |
ArcSin has to be calculated | |
ArcCos has to be calculated |
12 The Hungarian Naming Convention
A Hungarian Programmer came up with a brilliant idea , you place a letter or a few letters
in front of the name of your variable to describe the variable . This is now also applied
to functions and subroutines
I have used variable names like nMyInteger nCounter nRecordNr to name Integers and
sMystring sName sSurname sAddress to name Strings
Prefix |
Short Prefix |
Variable Type/Object |
bln | b | Boolean |
byt | Byte | |
cbo | Combo Box | |
cdl | Common dialog | |
chk | Check Box | |
cmd | CommandButton | |
cur | c | Currency |
dat | Data control | |
dbc | Data Bound ComboBox | |
dbg | Data Bound Grid | |
dbl | Data Bound ListBox | |
dbl | d | Double |
dir | Directory list box | |
dlg | Common dialog | |
drv | Drive list box | |
fil | File list box | |
fra | Frame | |
frm | Form | |
grd | Grid | |
hsb | Horizontal scroll bar | |
img | Image | |
int | n | Integer |
lbl | Label | |
lin | Line | |
lng | l | Long |
lst | List box | |
mnu | Menu | |
ole | OLE Container | |
opt | Option button | |
pic | Picture | |
shp | Shape | |
sng | f | Single |
sta | StatusBar | |
str | s | String |
tlb | Toolbar | |
tmr | Timer | |
txt | TextBox | |
vnt | v | Variant |
vsb | VerticaL Scroll bar |
13 Writing Procedures (Functions & Subroutines)
There comes a time when you want to have additional functionality you may
want to Calculate VAT or Control Motors
Lets put it this way if we were not able to write subroutines and Functions we would
be writing a very large programs
By using functions we can save time re-writing the same functionality many times in a program.
I like my main program to be short no more that 20 lines long and all the
functionality located in a Module, Class or Header file
now I can break my program into many small logical units
Subroutines
Subroutines may be called by your program and when they have
completely run control is returned to the program that called them
Here are a few examples of subroutines
in Visual Basic
Sub Mysub( )
begin
............ my code goes here
end
Sub Mysub2(PassValue as String )
begin
............ my code goes here
end
to call this subroutine just place its name in you code
'..............myprogram starts here
Mysub
Mysub2 "Hello"
Call Mysub2("Hello there")
'.............my program ends here
C++ & Java don't have subroutines void functions are used to do this
Functions
Functions are like subroutines however they return
a value . This means you need to use the function in an expression where the function is
assigned to a variable.This results in the calculation in the function is saved in this
variable
in Visual Basic
Function MyFunction( ) As String
begin
............ my code goes here
end
Function MyFunction2 ( PassValue as String ) As String
begin
............ my code goes here
end
in C++ and Java
void vMyfunction( void) // this is equivalent to a VB Subroutine
{
............ my code goes here
}
integer nMyfunction( void)
{
............ my code goes here
}
integer nMyfunction( integer nPassvalue)
{
............ my code goes here
}
14 Global and Local Variables(The life and Availability of a Variable)
Local Variables
Variables declared in a function / Subroutine can only be accessed by the
code within the function/Subroutine
VB uses the DIM statement when declaring local variables
Global Variables
Some Variables can be declared in a Module and can be
accessed throughout the program
VB uses the Public statement when declaring the global variable
Some programmers use global variables and get the subroutines to put values into
them
15 Using Windows GUI Form Components (to give your program the professional look)
The above form illustrates the most common components used when developing Windows applications
Labels used to display Static messages on the form
TextBox is used to display and get text the White Area is user editable
The Option Button(Radio Button) is used for selecting one from many choices
The Check Box is used to allow the user to get a Yes/No True/False input from the User
Scroll Bars are used to allow the user to enter a slider
varying value which the user can vary by sliding the slider bar
All the above components are placed on the form and each has its
16 Using External Code Files (Libraries ,Modules, Header files,Source Files,TPUs & TPLs)
Why re-invent the wheel every time you write a program. Would it be nice for you to create a Library of usefull routines that you can use every time you program.
Turbo Pascal & Delphi have a Unit called a TPU (TurboPascal Unit)
C++ has Source files and headers where you can define your usefull routines and code them
VB has Modules and Classes which you can use to put usefull functions /
methods that you can use when you write future programs
This is very language specific however it is good to know that you can re-use code.
OOP (Object Orientated Programming)
One of the most popular mechanisma for code reuse in the OOP Class.
The Class is coded in one place in you program and you can then make many
Object Instances of this Class
Classes offer something unique and most desireable that has made OOP popular and
that is High Security
A Class will have Variables known as Properties and
Functions known as Methods
The Classes have a builtin secutity mechanism.
You can determin which methods and properties can be accessed by Object
instances of your class this security is very tight and it makes your program very secure
and very reliable
17 Programming Techniques ( Binary Searches, Sorts, Simple Encryption)
The Binary Search
Imagine if I gave you a list of numbers 1 2 3 4 5 6 7 8 9 10
I told you to select one and not tell me lets say you selected 9
I have three questions to find it
1 Is it smaller than 6 No
I eliminate the first half
2 Is it smaller than 9 No
I eliminate the third quarter
3 Is it greater than 9 No
The answer the number is 9
Method
You arbitrarily break your search in half and test for one half and
eliminate one half
now we break the remaining half in half and repeat until you find the number
_________________________________________________________________________________________________
The Bubble Sort
If I want to sort an array with 10 numbers I create a second array and do the
following
I use a loop and a temporary variable going through all the numbers in the array
you want to sort testing and replacing the value of the temporary variable with the number
in the array if it is larger
This means you repeatedly remove the largest number and store in a second array
one at a time till you reach the last number
at this time you will have sorted the original array of numbers in the second array
_________________________________________________________________________________________________
The Michael Double Bubble Sort
This is a variation of the Bubble Sort. However every iteration of the loop I find
the largest and smallest number and save these at both extreems of the second array moving
towards the center of the second array
_________________________________________________________________________________________________
Simple Encryption
Suppose you wanted to encrypt a string "Hello" if we converted
this string into 8bit numbers for each letter using the ASC( )
Function you will get 4 numbers . Now if we inverted the bits using
XOR(number,255 ) function and convert the new numbers back to
characters using the CHR( ) function you will now have some funny characters
which make no sense.
To decrypt the encrypted text you re-encrypt it using the same process and Walla you get "Hello"
Encrypting Documents
This is fine for encrypting strings however you may want to encrypt a
document or a spread sheet to do that I use a different technique
I generate a file with 16000 or more random numbers . this becomes my
encryption key. I prompt the user for a password and convert all the characters to numbers
and calculate an Offset from the first random number now I test each character in
the document and if the are alphanumeric than I use the next random number and EXOR the
random number with the ASCII value of the alphanumeric character
To Decrypt I repeat the above process
The following techniques are used to find the bug in you program
19 Testing Your Code (Using Stubs & Drivers)
To test your procedure MyProc( ) you write a stub and a driver
The Driver
The best way to test the MyProc function is to write another test
procedure the Driver that calls it passing a prepared sequence of data to
feed it.
The Stub
Having written a driver you now write another procedure the
Stub and modify the MyProc procedure to call
the stub . The Stub is made to monitor what data is received from the MyProc
procedure
So what now ? I used a simple but reliable form of version control and
that is to create subfolders in my project folder
ProjectX001
ProjectX002 ..........etc
each time I start working I copy my working project to the next version
backup folder
I find this useful to see why a change failed and it allows me to cut-back to
the previous version quickly
I even backup all my previous version folders together with the current project folder to
CD every .
At my work we have even got the customer to sign his specification
and only deliver that in the current version
with the understanding that additional changes will be introduced in the next
release
Using a Program/ Module Version Documenting Template
This is an example of a Program Documentation Template
'|==============================================================================|
'|
|
'| Programm Name:N_Michael_01 Module Name: INI FILE CLASS
|
'| Program Version:1.4 Module Version:
1.0.1
|
'| Version Date: 14/09/1999 Next Review date:14/09/2000
|
'| Revision History:
|
'|
|
'|
|
'|
|
'|
|
'| Program Owner:N.Michael
|
'| Program Reviewer:U Fool
|
'|
|
'|
|
'|
|
'|==============================================================================|
'############################### INI FILE CLASS ##############################
'# Description: This Class creates/reads and writes to an INI file
#
'# It simplifies the addition of INI files to your project
#
'#
#
'# CLASS :IniFileClass.cls
#
'# Version: 1.0 Version Date 9/5/1999
#
'# Author : N Michael
#
'#
#
'############################################################################
21 Software Quality Control (ISO9001 Standard)
Although this is a Quality Control Document requiring quality
procedures , conducting audits and the maintenance of records
It also calls for companies to get their developers and project managers to
Plan development and testing of the software as well as the verification of the
software meeting the customers specification.
It is not the scope of this document to cover the entite ISO9001 standard by to look at sections that are relevant to the other sections covered in this document or what may be valuble for the Developer of tomorrow.
A The development plan
Identification of related plans such as :
B The Development Plan Phases
The development plan should define a process for transforming the customers specification
This involves dividing the work into phases
C Testing and validation
Testing is required at many levels from subroutine to module to program
1 Test Planning
2 Testing
3 Validation
D Configuration management
Configuration management provides a mechanism for identifying controlling and
tracking versions of each software item
In many cases earlier versions still in use must also be maintained and controlled
E Change Control
Software houses are required to establish and maintain procedures to
identify , document , review and authorize any changes to software
components.
Before any changes are accepted its validity should be confirmed and the
affects on other items should be identified and examined
There should be tractability between the changes and modified parts of software
items
F Product measurement
There are no universally accepted measures of software quality
However at a minimum measurement can be made of the number of field failures
and or defects from the customers viewpoint
G The Assessment of Sub Contractors
sub contractors should be assessed on the basis of their ability to
meet sub contract requirements, including quality requirements
the supplier shall establish and maintain records of acceptable sub contractors
Return to Nico's Visual Basic Page
(/SiliconValley/Peaks/2852/VB_Charts.html)
This page hosted by Get your own Free Home Page