visual basic: an object oriented approach 5: structured programming

22
Visual Basic: An Object Oriented Approach 5: Structured Programming

Upload: samantha-walker

Post on 11-Jan-2016

218 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Visual Basic: An Object Oriented Approach 5: Structured Programming

Visual Basic: An Object Oriented Approach

5: Structured Programming

Page 2: 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’

Page 3: Visual Basic: An Object Oriented Approach 5: 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

Page 4: Visual Basic: An Object Oriented Approach 5: Structured Programming

Program Control Constructs Three main structuring principles

Code statements should be grouped into functional units

Subs, Functions Possible to select whether one or more

statements will execute or not, based on a simple logical criterion

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

Page 5: Visual Basic: An Object Oriented Approach 5: Structured Programming

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

Page 6: Visual Basic: An Object Oriented Approach 5: Structured Programming

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

Page 7: Visual Basic: An Object Oriented Approach 5: Structured Programming

Conditions to control flow… Using a condition, can direct the

flow of a program…

If Time > “12:00” Then

MsgBox “Good afternoon”

End If

Page 8: Visual Basic: An Object Oriented Approach 5: Structured Programming

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

Page 9: Visual Basic: An Object Oriented Approach 5: Structured Programming

Iteration Iteration is repetition of code

Can execute one or more statements A given number of times Until a condition becomes True While a condition remains True

This allows the same code to be reused For a number of similar variables For the same variable(s) containing a succession of

values e.g Print a number of pages e.g. Get input from a user until a valid entry e.g. Calculate a succession of loan payments

Page 10: Visual Basic: An Object Oriented Approach 5: Structured Programming

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 <> “”

Page 11: Visual Basic: An Object Oriented Approach 5: Structured Programming

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

Page 12: Visual Basic: An Object Oriented Approach 5: Structured Programming

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

Page 13: Visual Basic: An Object Oriented Approach 5: Structured Programming

Arrays

StudentsJohn Smith

Jane Green

Mary Brown

Mike Stone

Ashok Din

Profits

1240.00

1775.50

1602.45

1100.70

1450.25

1825.23

1743.10

1250.50

1603.33

1733.24

1679.95

1432.55

1998 1999 2000

1

2

3

4

123456

Quarters

1-Dimensional Array

2-Dimensional Array

ElementIndex

IndexDim Students(1 To 6)Dim Students(1 To 6)Dim Profits(1998 To 2000, 1 To 4)Dim Profits(1998 To 2000, 1 To 4)

Page 14: Visual Basic: An Object Oriented Approach 5: Structured Programming

Programming with Arrays Strong affinity between arrays and

For..Next loops…

For Student_No = 1 To 6Print Students(Student_No)

Next

For Year = 1998 To 2000 ‘ Note – a nested For loop

For Quarter = 1 To 4TotalProfit = TotalProfit + Profits(Year,

Quarter)Next

Next

Page 15: Visual Basic: An Object Oriented Approach 5: Structured Programming

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

Page 16: Visual Basic: An Object Oriented Approach 5: Structured Programming

A User Defined Type 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

Type Student Name As String DOB As Date Address As String Level As IntegerEnd 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

Type Student Name As String DOB As Date Address As String Level As IntegerEnd 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

Page 17: Visual Basic: An Object Oriented Approach 5: Structured Programming

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) = SEnd Sub

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) = SEnd Sub

Page 18: Visual Basic: An Object Oriented Approach 5: Structured Programming

Error Handling Three types of error to deal with

Syntax errors – violation of language rules Visual Basic will detect and highlight these

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

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

Page 19: Visual Basic: An Object Oriented Approach 5: Structured Programming

Coping with run-time errors Three options…

Code around 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 Ignore them

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

Page 20: Visual Basic: An Object Oriented Approach 5: Structured Programming

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 IfEnd Sub

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 IfEnd Sub

Call to IsDate( ) function prevents a possible error

Page 21: Visual Basic: An Object Oriented Approach 5: Structured Programming

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

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

Page 22: Visual Basic: An Object Oriented Approach 5: Structured Programming

Adding an Error Handler

Sub Calculate_Age()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: If Err Then 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 IfEnd Sub

Sub Calculate_Age()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: If Err Then 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 IfEnd Sub

Error handling

starts here

Where to go in the event of an

error