Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Visual Basic: An Object Oriented Approach 5: Structured Programming."— Presentation transcript:

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

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

3 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

4 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

5 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

6 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

7 Conditions to control flow… Using a condition, can direct the flow of a program… If Time > “12:00” Then MsgBox “Good afternoon” End If

8 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

9 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.gPrint a number of pages e.g.Get input from a user until a valid entry e.g. Calculate a succession of loan payments

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

11 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

12 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

13 Arrays Students John 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 12341234 123456123456 Quarters 1-Dimensional Array 2-Dimensional Array Element Index Dim Students(1 To 6) Dim Profits(1998 To 2000, 1 To 4)

14 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

15 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

16 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 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 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

17 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 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

18 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

19 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

20 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 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

21 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

22 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 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 Sub Error handling starts here Where to go in the event of an error


Download ppt "Visual Basic: An Object Oriented Approach 5: Structured Programming."

Similar presentations


Ads by Google