functions, procedures, events

33
Functions, Procedures, Events Chapter 6

Upload: rimona

Post on 11-Jan-2016

35 views

Category:

Documents


1 download

DESCRIPTION

Functions, Procedures, Events. Chapter 6. Overview. Subroutines Sub-procedures Invoked sub-procedures Functions Scope Parameters The object model Properties Methods Events Event-handling procedures Testing Format function. Sub-procedures & Functions. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Functions, Procedures, Events

Functions, Procedures, Events

Chapter 6

Page 2: Functions, Procedures, Events

Overview Subroutines

Sub-procedures Invoked sub-procedures

Functions Scope Parameters

The object model Properties Methods Events

Event-handling procedures Testing Format function

Page 3: Functions, Procedures, Events

Sub-procedures & Functions

Sub-procedures and functions are ways of writing code once, but using in many different places Calculate the square root of a number Display the updated totals in a cash register program

How do functions & sub-procedures differ in VB? functions return values, sub-procedures do not

Sub-procedures & functions require a name may have local variables may require arguments

Page 4: Functions, Procedures, Events

Sub-procedures

All of our button pushing “events” invoke sub-procedures that are executed when the event occurs

There are some things, however, that we want to do as part of several different event handlers

To do this we can write sub-procedures that are not connected with specific events, but can be called anywhere within a program This code re-use can simplify the writing and debugging of an

VB application

Page 5: Functions, Procedures, Events

Using sub-procedures

The format for sub-procedure declaration is

Private Sub <Name> ( <Para1> as <Type1>, …)

The parentheses surround the procedure’s parameter list One of the most useful aspects of procedures is that they

can be used given different inputs each time they are called

Page 6: Functions, Procedures, Events

Using Sub-procedures

The format for procedure invocation is

<Name> <Arg1>, <Arg2>, …

When a procedure is invoked, each parameter is matched with the corresponding argument the parameter is used a a place holder for the particular

argument passed to the sub-procedure Changes to the parameter are reflected in the argument

Page 7: Functions, Procedures, Events

Advantages

Using sub-procedures … allows for efficiency in that code used by multiple

buttons can be written once permits easier debugging

An error need be fixed only once forces you to organize your thoughts allows for complicated sub-procedures to be written by

experts and then used by all

Page 8: Functions, Procedures, Events

Procedure ExamplePrivate Sub DisplayPay(curShiftPremium as Currency, _

curBaseRate as Currency, _ intBillableHours as Integer, _

intUnbilledHours as Integer, _ dblPrem as Double) Dim curHourlyRate as Currency Dim intHrsWorked as Intger curHourlyRate = (curShiftPremium + curBaseRate)*dblPrem intHrsWorked = intBillableHours + intUnbilledHours curTotalPay = curHrlyRate * intHrsWorked MsgBox "Total Pay is " & curTotalPayEnd Sub

Private Sub cmdGo_Click()DisplayPay curSP, curA + curB, val(txtBill), val(txtUn), dblPrEnd Sub

Page 9: Functions, Procedures, Events

Functions If the main purpose of the repeated code is to calculate a

value, functions are a better choice than procedures

Private Function curPay (curHrlyRate as _Currency, curHours as Currency) as Currency…

End Function

Once declared, you can invoke new function in the same way you called the functions built into VB, like Val

curMyPay = curPay(curRate, curHrs)

Page 10: Functions, Procedures, Events

Function Example

Private Function CalculatePay(curShiftPremium as Currency, _ curBaseRate as Currency, _ intBillableHours as Integer, _ intUnbilledHours as Integer, _ dblPrem as Double) as Currency Dim curHourlyRate as Currency Dim intHrsWorked as Intger curHourlyRate = (curShiftPremium + curBaseRate)*dblPrem intHrsWorked = intBillableHours + intUnbilledHours CalculatePay = curHrlyRate * intHrsWorkedEnd Function

Private Sub cmdGo_Click() lblA.Caption = _ CalculatePay (curSP, curB, val(txtBill), val(txtUn), dblPr)End Sub

Page 11: Functions, Procedures, Events

Objects: Properties, Methods & Events

Each item in the toolbox defines an “object” type Objects have “properties”

Each property is, itself, either an object or data type• The .caption property of a Label is of the string data type

The values can be modified using the properties window, or in code

Objects recognize “events” Like click and load The exact events vary from object type to object type VB programmer can write code which responds to these events

Object may be acted upon by “methods” A method changes the appearance, properties, or other feature on an object

• Methods are object-local procedures

Page 12: Functions, Procedures, Events

Responding to Events

When an event is detected by a VB object, VB attempts to invoke the event handling sub-procedure associated with that event You may invoke event handlers as normal sub-

procedures The name of an event handling sub-procedure must

be of the form: <control name>_<event name> For example:

cmdName_Click lblName_MouseMove

Page 13: Functions, Procedures, Events

Invoking Methods

Methods are sub-procedures that are associated with a particular object

Invoking the method will change that object, but should have little other effect

Methods do not return a value Example: calling the move method of a label

Private Sub cmdMove_Click() lblMoving.Move 1, 1, 5, 2End Sub

Page 14: Functions, Procedures, Events

Icons

In the illustration below “Caption” and “ClipControls” are Properties and “Circle” and “Cls” are Methods. This is the auto completion popup window that VB displays after typing the name of a Label followed by a “.”

Page 15: Functions, Procedures, Events

Event Generating Control: the Timer

The timer control can be used to generate an event after a delay, or recurring events at regular intervals

In design view, when you place a timer on a form it appears as a tiny stop watch

At run-time, timer controls are always invisible

Page 16: Functions, Procedures, Events

Timer: the interval property Each timer control has an Interval property that

specifies the number of milliseconds that pass between one timer event to the next Unless it is disabled, a timer continues to receive an

event at roughly equal intervals of time The Interval property has a few limitations to

consider when you're programming a timer control: The interval can be between 0 and 64,767

The longest interval is about 64.8 seconds The interval is not guaranteed to elapse exactly on

time Even though the Interval property is measured in

milliseconds, the true precision of an interval is no more than one-eighteenth of a second

Page 17: Functions, Procedures, Events

Timer: the Enabled property

Enabled is a Boolean property If you want the timer to start working as

soon as the form loads, set it to True Otherwise, leave this property set to False

You might choose to have the click of a command button start operation of the timer Then you would have to assign true to the

enabled property of the timer in the buttons click event handler

Page 18: Functions, Procedures, Events

Randomize and Rnd

The Randomize statement initializes VB's random number generator

The Rnd function returns random numbers in the range 0 to 1 including 0 not including 1

To use rnd to generate random integers:Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Page 19: Functions, Procedures, Events

The VB Debugger

Now that we are writing slightly longer programs, it will be useful for us to examine the VB debugger The debugger is part of the VB IDE With the debugger you can

Stop your program when a certain line is reached Inspect the values stored in variables & properties Change the values stored in variables and properties

Demonstration of debugger and immediate window

Page 20: Functions, Procedures, Events

Program Testing

Programs must be tested carefully in order to ensure that they work as planned Testing is not a casual thing

There is a problem with real programs, they are so complicated that it takes a very long time to understand the program, rather than the computer error

Page 21: Functions, Procedures, Events

Black Box Testing

Usually done from the program specifications No knowledge of how the program actually does what it

does Often done by a separate design team

The problems that need to be solved are usually very large. The examples we use are often too simple to need the solution techniques.

Page 22: Functions, Procedures, Events

Example 1: Black Box

Problem: Read two numbers, ‘a’ and ‘b’. Put the larger of the numbers into the box ‘c’. Conditions to be tested:

Page 23: Functions, Procedures, Events

Example 1: Black Box both numbers positive

a larger b larger

one number positive a positive, not b b positive, not a

both numbers negative a larger (less negative)

b larger

one number zero a = 0 b = 0

both numbers equal both positive both negative both zero

other conditions...

Page 24: Functions, Procedures, Events

Example 2: Black Box

Test a program that shows the name of the next day each time the “Next Day” button is clicked.

Seems to work ok.

Page 25: Functions, Procedures, Events

White Box Testing

Uses details of just how the program works. Exhaustive test of each routine used. In real world cases, complete testing is just not possible. Requires a careful choice of just how testing is done.

Page 26: Functions, Procedures, Events

Format Function

Format function - returns a formatted expression

Syntax: Format(expression, format)

Some of Visual Basic’s predefined formats: Currency

Fixed

Standard

Percent

Page 27: Functions, Procedures, Events

Format Examples

FormatCurrency(1234) or

Format(1234, “Currency”)

$1,234.00 or 1.234,00

Format(1234, “$#,###.00”)

$1,234.00

FormatNumber(1234)

1,234.00 or 1.234,00

FormatDateTime(“20:10”,vbLongTime)

20:10:00

Page 28: Functions, Procedures, Events

Named Format and Descriptions

General Number: No special formatting

Currency: Thousands separator, two digits to the right of the decimal

Fixed: At least one digit to the left and two digits to the right of the decimal

Standard: Thousands separator, at least one digit to the left and two digits to the right of the decimal

Page 29: Functions, Procedures, Events

Named Format and Descriptions

Percent: Multiplies by 100 and follows number by % sign

Scientific: Standard scientific notation

Yes/No: Displays Yes for a nonzero value

True/False: Displays True for a nonzero value

On/Off: Displays On for a nonzero value

Page 30: Functions, Procedures, Events

Codes for Numeric Formats 0 – Digit placeholder: Displays the digit or 0 if no digit.

9 – Digit placeholder: Displays the digit or displays nothing if no digit. (omits leading and trailing zeros)

. – Decimal separator: Indicates where the decimal point is displayed.

Page 31: Functions, Procedures, Events

Codes for Numeric Formats , – Thousands separator: Indicates where the separators

are displayed.

% – Percentage indicator: Indicates where a percent sign is displayed. (number multiplied by 100)

E-,E+ - Scientific notation: With E- a minus sign is displayed next to negative exponents, no sign for positive.

Page 32: Functions, Procedures, Events

Named Date and Time Formats General Date: Displays date and time if

expression contains both.

Long Date: Displays the day of the week, the day of the month, the month and the year.

Medium Date: Displays the day of the month, a three-letter abbreviation for the month and the year.

Short Date: Displays the day, month, the month and year.

Page 33: Functions, Procedures, Events

Named Date and Time Formats Long Time: Displays hours, minutes, and

seconds along with the AM/PM indicator.

Medium Time: Displays hours and minutes along with the AM/PM indicator.

Short Time: Displays hours and minutes in military time