Transcript Chapter5
Visual Basic: An Object
Oriented Approach
5: Structured Programming
Structures within Software
Structure is apparent at a number of levels
A project can involve a number of modules, each
occupying a separate file
Each module will contain a number of procedures
(Subs and Functions) and variable declarations
Within a Sub or Function, certain standard code
constructs are used to define whether actions
happen or not, or how often they are executed
Data variables in a module can be grouped in
several ways to form data structures
The last two categories are central to the
idea of ‘Structured Programming’
Structured Programming
Born out of chaotic nature of software
designs before late 1960s
Idea is to limit the power of the programmer
to direct a program with no restrictions
Code statements are organised in a small
number of standard forms
Structure of data should mirror real-life
information structure wherever possible
Program Control Constructs
Three main structuring principles
Code statements should be grouped into
functional units
Possible to select whether one or more
statements will execute or not, based on a simple
logical criterion
Subs, Functions
If..Then, If..Then..Else, Select Case
Possible to repeat a statement or group of
statements either a given number of times or until
a specific condition is true
For..Next, Do..Loop
Conditions
Central to the principles of programming
The flow of execution depends on prevailing
conditions within a program
A condition is an expression that evaluates to
True or False. Can be…
A single Boolean variable
A combination of Boolean variables
The result of a comparison for equality or relative
size
A combination of such comparisons
Conditions
X=0
‘ True if X is zero, False otherwise
Y=X
‘ as above
X<Y
‘ True is X is not equal to Y or
‘ bigger than it
X = 0 And Y >2
‘ True is both are true
X = 0 Or Y > 2
‘ True is either is true
Conditions to control flow…
Using a condition, can direct the flow of
a program…
If Time > “12:00” Then
MsgBox “Good afternoon”
End If
Can use If..Then flexibly…
If Time < “12:00” Then
MsgBox “Good morning”
ElseIf Time > “12:00” And Time < “18:00” Then
MsgBox “Good afternoon”
Else
MsgBox “Good evening”
End If
Iteration
Iteration is repetition of code
Can execute one or more statements
This allows the same code to be reused
A given number of times
Until a condition becomes True
While a condition remains True
For a number of similar variables
For the same variable(s) containing a succession of
values
e.g
e.g.
e.g.
Print a number of pages
Get input from a user until a valid entry
Calculate a succession of loan payments
Iteration
For index = 1 To 12
‘ Print a table of squares
Print index, index * index
Next
Do
‘ Repeat until user enters name
Name = InputBox(“Enter your name”)
Loop Until Name <> “”
Structured Data
Individual variables are awkward in many
circumstances
Usually need to work with sets of data
Classes of students
Lists of library books
Normally, information is complex and has structure
Items are related by..
Similarity (e.g. class of students)
Hierarchy (e.g. a book has several chapters)
Grouping (e.g. a person has a name, address, phone number,
national insurance number, several credit cards, etc..)
We use data structures to group information together
Arrays
Simplest form of data structure
A number of variables of the same type,
related in some way
A list of names
A Table of profit figures
All elements share the same name
Each element has an index indicating its
position in the array
Arrays
Dim Profits(1998 To 2000, 1 To 4)
Dim Students(1 To 6)
Index
Students
1
2
3
4
5
6
John Smith
Jane Green
Mary Brown
Mike Stone
Ashok Din
Profits
Quarters
1
2
3
4
1998
1999
2000
1240.00
1450.25
1603.33
1775.50
1825.23
1733.24
1602.45
1743.10
1679.95
1100.70
1250.50
1432.55
1-Dimensional Array
Index
2-Dimensional Array
Element
Programming with Arrays
Strong affinity between arrays and
For..Next loops…
For Student_No = 1 To 6
Print Students(Student_No)
Next
For Year = 1998 To 2000
‘ Note – a nested For loop
For Quarter = 1 To 4
TotalProfit = TotalProfit + Profits(Year, Quarter)
Next
Next
User Defined Types
Arrays group a number of similar items
together (e.g. a List of…). Items share a
name.
Sometimes it is necessary to group related
items of different type together (e.g.
someone’s Name, Address, Date of Birth,
Phone_No etc.)
A User Defined Type allows a number of
different variables with distinct names to be
grouped into Records
A User Defined Type
Type Student
Name As String
DOB As Date
Address As String
Level As Integer
End Type
‘ A single Student…
Dim S As Student
‘ An array of them…
Dim Class(1 To 20) As Student
‘ A useful index variable…
Dim StudentCount As Integer
A template for compound
variables
Each individual member has
its own name and type
Some similarities to Classes
Must define a UDT before
declaring variables of the type
Access individual members using
a dot (.) notation
Defines a package of data
Programming UDTs
Sub CreateStudentRecord()
‘ Assign values to student record fields…
S.Name = InputBox(“Enter student’s name”)
S.Address = InputBox(“Enter student’s address”)
S.DOB = InputBox(“Enter student’s date of birth”)
S.Level = InputBox(“Enter year enrolled for (1..3)”)
‘ Now increment the index to be used with the Class array…
StudentCount = StudentCount + 1
‘ and copy the student record (note – a single assigment)…
Class(StudentCount) = S
End Sub
Error Handling
Three types of error to deal with
Syntax errors – violation of language rules
Logic errors – the code does not do what you intend
it to
Only solution is experience – learn how to design and
implement algorithms, take care.
Run-time errors – things that are normally not
anticipated
Visual Basic will detect and highlight these
e.g. ask the user to enter a number, but get a letter
e.g. try to access a disk that is not in the drive
e.g. try to do impossible operation ( x/0)
Need to deal with Run-Time errors in programs
Coping with run-time errors
Three options…
Code around them
Ignore them
Always check user inputs for type and sense, check for
drive availability etc.
Can lead to excess code and programs that are difficult
to follow
Turn off error checking
Dangerous – may look as if a result has been reached
but likely to be wrong
Build error trapping code
Break code into ‘Normal’ flow code and ‘Error Handling’
Define how to react if an error occurs
Coding around an error
Sub Calculate_Age()
Dim DOB As String
DOB = InputBox("Enter your date of birth.")
If IsDate(DOB) Then
MsgBox "You are " & (Date – Cdate(DOB))/365 & " years old."
Else
MsgBox "Invalid date."
End If
End Sub
Call to IsDate( ) function prevents a
possible error
Ignoring an error
Sub Calculate_Age()
Dim DOB As Date
On Error Resume Next
DOB = InputBox("Enter your date of birth.")
MsgBox "You are " & (Date - DOB) / 365 & " years old."
End Sub
On Error Resume Next causes VB to ignore
run-time errors – can lead to mistaken belief
that a wrong answer is correct
Adding an Error Handler
Where to go in the
Sub Calculate_Age()
event of an error
Dim DOB As Date
On Error GoTo err_Calculate_Age
DOB = InputBox("Enter your date of birth.")
MsgBox "You are " & (Date - DOB) / 365 & " years old."
err_Calculate_Age:
Error handling
If Err Then
starts here
If Err = 13 Then ' Type mismatch - we expected this.
MsgBox "An invalid date has been entered."
Resume
Else
MsgBox Error.Description ‘ Some errors can never be anticipated.
End If
End If
End Sub