1 / 33

Functions, Procedures, Events

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.

rimona
Download Presentation

Functions, Procedures, Events

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions, Procedures, Events Chapter 6

  2. Overview • Subroutines • Sub-procedures • Invoked sub-procedures • Functions • Scope • Parameters • The object model • Properties • Methods • Events • Event-handling procedures • Testing • Format function

  3. 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

  4. 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

  5. Using sub-procedures • The format for sub-procedure declaration isPrivate 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

  6. 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

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

  8. Procedure Example Private 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 " & curTotalPay End Sub Private Sub cmdGo_Click() DisplayPay curSP, curA + curB, val(txtBill), val(txtUn), dblPr End Sub

  9. 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)

  10. 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 * intHrsWorked End Function Private Sub cmdGo_Click() lblA.Caption = _ CalculatePay (curSP, curB, val(txtBill), val(txtUn), dblPr) End Sub

  11. 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

  12. 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

  13. 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

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

  15. 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

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

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

  18. 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)

  19. 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

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

  21. 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.

  22. 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:

  23. 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... Example 1: Black Box

  24. 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.

  25. 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.

  26. Format Function • Format function - returns a formatted expression • Syntax: Format(expression, format) • Some of Visual Basic’s predefined formats: • Currency • Fixed • Standard • Percent

  27. 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

  28. 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

  29. 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

  30. 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.

  31. 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.

  32. 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, themonth 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.

  33. 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

More Related