procedures and modular design · •avoid logical errors •efficiency •debugging. chapter 4 - vb...
TRANSCRIPT
Chapter 4 - VB 2005 by Schneider 1
Procedures and Modular Design
September 20, 2006
Chapter 4 - VB 2005 by Schneider 2
Today…
• On to Chapter 4
Chapter 4 - VB 2005 by Schneider 3
Friday…
• Assignment 2!
Chapter 4 - VB 2005 by Schneider 4
Chapter 4 - GeneralProcedures
• 4.1 Sub Procedures, Part I
• 4.2 Sub Procedures, Part II
• 4.3 Function Procedures
• 4.4 Modular Design
Procedures are an important part ofprogramming in general…
Chapter 4 - VB 2005 by Schneider 5
4.1 Sub Procedures, Part I
• Sub Procedures
• Variables and Expressions as Arguments
• Calling Other Sub Procedures
Chapter 4 - VB 2005 by Schneider 6
Devices for modularity
• Why do we want to split things up?• Readability
• Avoid logical errors
• Efficiency
• Debugging
Chapter 4 - VB 2005 by Schneider 7
Devices for modularity
• Visual Basic has two devices forbreaking problems into smaller pieces:• Sub procedures
• Function procedures
Chapter 4 - VB 2005 by Schneider 8
Sub Procedures
• Perform one or more related tasks
• General syntax
Sub ProcedureName()
statements
End Sub
Chapter 4 - VB 2005 by Schneider 9
Calling a Sub procedure
• The statement that invokes a Subprocedure is also referred to as a callstatement.
• A call statement looks like this:ProcedureName()
Chapter 4 - VB 2005 by Schneider 10
Naming Sub procedures
• The rules for naming Sub procedures arethe same as the rules for namingvariables.
• You can choose whatever you like……but ultimately, the best choice is astrong description of what the proceduredoes…• E.g. AddTwoNums()
Chapter 4 - VB 2005 by Schneider 11
Sub ExplainPurpose()
ExamplelstBox.Items.Clear()ExplainPurpose()lstBox.Items.Add("")
lstBox.Items.Add("Program displays a sentence")
lstBox.Items.Add("identifying a sum.")
End Sub
Chapter 4 - VB 2005 by Schneider 12
Passing Values• You can send values to a Sub procedure Sum(2, 3)
Sub Sum(ByVal num1 As Double, ByVal num2 As Double) lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "."End Sub
• In the Sum Sub procedure, 2 will be stored in num1 and 3will be stored in num2
Chapter 4 - VB 2005 by Schneider 13
Arguments and Parameters
• Sum(2, 3)
Sub Sum(ByVal num1 As Double, ByVal num2 As Double)
arguments
parameters
displayedautomatically
Chapter 4 - VB 2005 by Schneider 14
Several Calling StatementsExplainPurpose()Sum(2, 3)Sum(4, 6)Sum(7, 8)
Output:Program displays a sentence identifying a sum.The sum of 2 and 3 is 5.The sum of 4 and 6 is 10The sum of 7 and 8 is 15.
Chapter 4 - VB 2005 by Schneider 15
Passing Strings and Numbers
• Demo("CA", 34)
Sub Demo(ByVal state As String, ByVal pop As Double) txtBox,Text = state & " has population " & pop & _ " million."End Sub
• Note: The statement Demo(34, "CA") would not be valid.The types of the arguments must be in the same order asthe types of the parameters.
Chapter 4 - VB 2005 by Schneider 16
Variables and Expressions asArguments
Dim s As String = "CA"Dim p As Double = 17Demo(s, 2 * p)
Sub Demo(ByVal state As String, ByVal pop As Double) txtBox.Text = state & " has population " & pop & _ " million."End Sub
• Note: The variable names in the arguments need not matchthe parameter names. For instance, s versus state..
Chapter 4 - VB 2005 by Schneider 17
CallingA Sub procedure can call another Sub procedure.
Private Sub btnAdd_Click(...) Handles btnAdd.Click Sum(2, 3) End Sub
Sub Sum(ByVal num1 As Double, ByVal num2 As Double) DisplayPurpose() lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "."End Sub
Chapter 4 - VB 2005 by Schneider 18
4.2 Sub Procedures, Part II
• Passing by Value
• Passing by Reference
• Local Variables
• Class-Level Variables
• Debugging
Chapter 4 - VB 2005 by Schneider 19
ByVal and ByRef
• Parameters in Sub procedure headersare proceeded by ByVal or ByRef
• ByVal stands for By Value
• ByRef stands for By Reference
Chapter 4 - VB 2005 by Schneider 20
Passing by Value
• When a variable argument is passed to aByVal parameter, just the value of theargument is passed.
• After the Sub procedure terminates, thevariable has its original value.
Chapter 4 - VB 2005 by Schneider 21
Example
Dim n As Double = 4 Triple(n) txtBox.Text = CStr(n)End Sub
Sub Triple(ByVal num As Double) num = 3 * numEnd Sub
Output: 4
Chapter 4 - VB 2005 by Schneider 22
Same Example: n num
Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num)End Sub
Sub Triple(ByVal num As Double) num = 3 * numEnd Sub
Output: 4
Chapter 4 - VB 2005 by Schneider 23
Passing by Reference
• When a variable argument is passed to aByRef parameter, the parameter is giventhe same memory location as theargument.
• After the Sub procedure terminates, thevariable has the value of the parameter.
Chapter 4 - VB 2005 by Schneider 24
ExamplePublic Sub btnOne_Click (...) Handles _ btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num)End Sub
Sub Triple(ByRef num As Double) num = 3 * numEnd Sub
Output: 12
Chapter 4 - VB 2005 by Schneider 25
Example: num nPrivate Sub btnOne_Click(...) Handles _ btnOne_Click Dim n As Double = 4 Triple(n) txtBox.Text = CStr(n)End Sub
Sub Triple(ByRef num As Double) num = 3 * numEnd Sub
Output: 12
Chapter 4 - VB 2005 by Schneider 26
ByVal and ByRef
Memory Location 1
ByVal Procedure Parameter
16
ByRef ProcedureParameter
Memory Location 116
This refers toanything stored in
this memory location
This refers to the value ofwhatever is in this
memory location…not thelocation itself
Any changes to this, donot effect what is storedin the memory location
1…it’s just a copy
Any changes to this doeffect what is stored in
the memory location 1…it’s not a copy
Chapter 4 - VB 2005 by Schneider 27
Local Variable
• A variable declared inside a Subprocedure with a Dim statement
• Space is reserved in memory for thatvariable until the End Sub…• …then the variable ceases to exist
Chapter 4 - VB 2005 by Schneider 28
Local VariablesPrivate Sub btnOne_Click(...) Handles btnOne_Click Dim num As Integer = 4 SetFive() txtBox.Text = CStr(num)End Sub
Sub SetFive() Dim num As Integer = 5End Sub
Output: 4
Chapter 4 - VB 2005 by Schneider 29
Local VariablesPrivate Sub btnOne_Click(...) Handles btnOne_Click Dim num As Integer = 4 SetFive() txtBox.Text = CStr(num)End Sub
Sub SetFive() Dim num As Integer = 5End Sub
Output: 4
num only existswithin this sub
procedure
this num iscompletely
unrelated to theone above
Chapter 4 - VB 2005 by Schneider 30
Class-Level Variables
• Visible to every procedure in a form’scode without being passed
• Dim statements for class-level variablesare placed• Outside all procedures
• At the top of the program region
Chapter 4 - VB 2005 by Schneider 31
Class-Level VariablesDim num As Integer = 4
Private Sub btnOne_Click(...) Handles btnOne_ClicktxtBox.Text = CStr(num)
SetFive() txtBox.Text &= CStr(num)End Sub
Sub SetFive() num = 5End Sub
Output: 45
Chapter 4 - VB 2005 by Schneider 32
Scope
• The scope of a variable is the portion ofthe program that can refer to it.
• In other words, the parts of the programthat can access that variable…
• …a variable is out of scope if it cannot bereferred to in that particular codesegment
Chapter 4 - VB 2005 by Schneider 33
Scope
• Class-level variables have class-levelscope and are available to allprocedures in the class.
• Variables declared inside a procedurehave local scope and are only availableto the procedure in which they aredeclared.
Chapter 4 - VB 2005 by Schneider 34
Debugging
• Programs with Sub procedures areeasier to debug
• Each Sub procedure can be checkedindividually before being placed into theprogram• This is sometimes called modularity
Chapter 4 - VB 2005 by Schneider 35
4.3 Function Procedures
• User-Defined Functions Having SeveralParameters
• Comparing Function Procedures withSub Procedures
• Collapsing a Procedure with a RegionDirective
Chapter 4 - VB 2005 by Schneider 36
Some Built-In FunctionsFunction Example Input Output
Int Int(2.6) is 2 number number
Math.Round Math.Round(1.23,1)is 1.2
number, number number
FormatPercent FormatPercent(.12)is 12.00%
number string
FormatNumber FormatNumber(12345.628, 1) is12,345.6
number, number string
Chapter 4 - VB 2005 by Schneider 37
Function Procedures
• Function procedures (aka user-definedfunctions) always return one value
• Syntax:Function FunctionName(ByVal var1 As Type1, _ ByVal var2 As Type2, _ …) As dataType statement(s) Return expressionEnd Function
Chapter 4 - VB 2005 by Schneider 38
Example: Form
txtFullName
txtFirstName
Chapter 4 - VB 2005 by Schneider 39
Example: CodePrivate Sub btnDetermine_Click(...) _ Handles btnDetermine.Click Dim name As String name = txtFullName.Text txtFirstName.Text = FirstName(name)End Sub
Function FirstName(ByVal name As String) As String Dim firstSpace As Integer firstSpace = name.IndexOf(" ") Return name.Substring(0, firstSpace)End Function
Functioncall
Returnstatement
Chapter 4 - VB 2005 by Schneider 40
Example: CodePrivate Sub btnDetermine_Click(...) _ Handles btnDetermine.Click Dim name As String name = txtFullName.Text txtFirstName.Text = FirstName(name)End Sub
Function FirstName(ByVal name As String) As String Dim firstSpace As Integer firstSpace = name.IndexOf(" ") Return name.Substring(0, firstSpace)End Function
the functioncall
"becomes"the value it
returns
Chapter 4 - VB 2005 by Schneider 41
Example: Form
txtSideOne
txtSideTwo
txtHyp
Chapter 4 - VB 2005 by Schneider 42
Example: CodePrivate Sub btnCalculate_Click(...) _ Handles btnCalculate.Click Dim a, b As Double a = CDbl(txtSideOne.Text) b = CDbl(txtSideTwo.Text) txtHyp.Text = CStr(Hypotenuse(a, b))End Sub
Function Hypotenuse(ByVal a As Double, _ ByVal b As Double) As Double Return Math.Sqrt(a ^ 2 + b ^ 2)End Function
Chapter 4 - VB 2005 by Schneider 43
User-Defined Function HavingNo Parameters
Private Sub btnDisplay_Click(...) _ Handles btnDisplay.Click txtBox.Text = Saying()End Sub
Function Saying() As String Dim strVar As String strVar = InputBox("What is your" _ & " favorite saying?") Return strVarEnd Function
Chapter 4 - VB 2005 by Schneider 44
Comparing Function Procedureswith Sub Procedures
• Subs are accessed using a callstatement
• Functions are called where you wouldexpect to find a literal or expression
• For example:• result = functionCall
• lstBox.Items.Add (functionCall)
Chapter 4 - VB 2005 by Schneider 45
Comparing Function Procedureswith Sub Procedures
• Subs are accessed using a callstatement
• Functions are called where you wouldexpect to find a literal or expression
• For example:• result = 5
• lstBox.Items.Add (“some string”)
Chapter 4 - VB 2005 by Schneider 46
Comparing Function Procedureswith Sub Procedures
• Subs are accessed using a callstatement
• Functions are called where you wouldexpect to find a literal or expression
• For example:• result = functionCall
• lstBox.Items.Add (functionCall)
Chapter 4 - VB 2005 by Schneider 47
Functions vs. Procedures
• Both can perform similar tasks
• Both can call other subs and functions
• Use a function when you want to returnone and only one value
Chapter 4 - VB 2005 by Schneider 48
Collapsing a Procedure with aRegion Directive
• A procedure can be collapsed behind acaptioned rectangle
• This task is carried out with a Region directive.• To specify a region, precede the code to be
collapsed with a line of the form#Region "Text to be displayed in the box."
• and follow the code with the line#End Region
• Makes code more readable
Chapter 4 - VB 2005 by Schneider 49
Region Directives
Chapter 4 - VB 2005 by Schneider 50
Collapsed Regions
Chapter 4 - VB 2005 by Schneider 51
4.4 Modular Design
• Top-Down Design
• Structured Programming
• Advantages of Structured Programming
Chapter 4 - VB 2005 by Schneider 52
Design Terminology
• Large programs can be broken downinto smaller problems
• "divide-and-conquer" approach called"stepwise refinement"
• Stepwise refinement is part of top-downdesign methodology
Chapter 4 - VB 2005 by Schneider 53
Top-Down Design
• General problems are at the top of thedesign
• Specific tasks are near the end of thedesign
• Top-down design and structuredprogramming are techniques to enhanceprogrammers' productivity
Chapter 4 - VB 2005 by Schneider 54
Top-Down Design Criteria1. The design should be easily readable and
emphasize small module size.2. Modules proceed from general to specific as
you read down the chart.3. The modules, as much as possible, should be
single minded. That is, they should onlyperform a single well-defined task.
4. Modules should be as independent of eachother as possible, and any relationshipsamong modules should be specified.
Chapter 4 - VB 2005 by Schneider 55
Top-Level Design HierarchyChart
Chapter 4 - VB 2005 by Schneider 56
Detailed Hierarchy Chart
Chapter 4 - VB 2005 by Schneider 57
Structured Programming• Control structures in structured programming:• Sequences: Statements are executed one
after another.• Decisions: One of two blocks of program code
is executed based on a test for somecondition.
• Loops (iteration): One or more statementsare executed repeatedly as long as a specifiedcondition is true.
Chapter 4 - VB 2005 by Schneider 58
Advantages of StructuredProgramming
• Goal to create correct programs that areeasier to• write
• understand
• modify
• "GOTO –less" programming
Chapter 4 - VB 2005 by Schneider 59
Comparison of Flow Charts
Chapter 4 - VB 2005 by Schneider 60
Easy to Write
• Allows programmer to first focus on thebig picture and take care of the detailslater
• Several programmers can work on thesame program at the same time
• Code that can be used in manyprograms is said to be reusable
Chapter 4 - VB 2005 by Schneider 61
Easy to Debug
• Procedures can be checked individually
• A driver program can be set up to testmodules individually before the completeprogram is ready
• Using a driver program to test modules(or stubs) is known as stub testing
Chapter 4 - VB 2005 by Schneider 62
Easy to Understand
• Interconnections of the procedures reveal themodular design of the program.
• The meaningful procedure names, along withrelevant comments, identify the tasksperformed by the modules.
• The meaningful variable names help theprogrammer to recall the purpose of eachvariable.
Chapter 4 - VB 2005 by Schneider 63
Easy to Change
• Because a structured program is self-documenting, it can easily be decipheredby another programmer.
Chapter 4 - VB 2005 by Schneider 64
Object-Oriented Programming
• an encapsulation of data and code thatoperates on the data
• objects have properties, respond tomethods, and raise events.