IS 350 Application Structure
Objectives Describe the parts of an application made up of multiple forms and classes Create and use Sub procedures Create and use Function procedures Work with applications made up of multiple forms Communicate data between forms Create reusable applications with custom classes having methods and properties
Common Application Elements Most Windows applications contain multiple forms and other parts as follows: Procedures Splash screens Other forms Developer-defined classes The concepts of scope and visibility become important in these applications
The Purpose of Procedures Procedures facilitate code reuse because they can be called by event handlers and other procedures The methods supplied by the .NET Framework class library are just procedures in a class WriteLine is a procedure in the System.Console class, for example Procedures are of two types: Sub procedures Function procedures
Introduction to Sub Procedures Sub procedures accept arguments Arguments are used to send information to a procedure Sub procedures accept 0, 1, or many arguments Sub procedures are used to perform a generic task that does not return a value
Declaring Procedure Arguments Data is sent to a procedure via arguments Syntax [ByRef | ByVal] argName [As argType] argName contains the name (identifier) of the argument Arguments are used in the same way as local variables argType contains the data type of the argument argType is required when strict type checking is enabled
Sub Procedure (example 1) Clear the contents of three text boxes Private Sub ClearTextBoxes() txtPrefix.Text = "" txtFirstName.Text = "" txtLastName.Text = "" End Sub
Sub Procedure (example 2) Format a text box passed as an argument txtArg is the argument name Private Sub FormatTextBox( _ ByVal txtArg As TextBox) txtArg.ForeColor = Color.LightBlue txtArg.BackColor = Color.DarkBlue End Sub
Calling Sub Procedures The optional Call keyword is used to call a Sub procedure The following statements are equivalent: Call ClearTextBoxes() ClearTextBoxes
Calling a Sub procedure
Introduction to Function Procedures A Function procedure accepts 0, 1, or many arguments Arguments are passed by reference or by value A Function procedure returns a value having a data type Return statement returns a value from a Function procedure Function procedures work like methods that return a value Call the Exit Function statement to exit the function immediately Public, Private, and Friend keywords define a procedure's scope Procedures appear in a Class or Module block
Function Procedure (example) A Function procedure named Square that calculates the square of its argument The procedure accepts one argument named argValue The data type of the argument is Double The procedure returns a value having a data type of Double Public Function Square(argValue As Double) _ As Double Dim LocalResult As Double LocalResult = argValue * argValue Return LocalResult End Function
Executing a Function Procedure Call the Function procedure named Square Procedure call appears on the right side of an assignment statement Store the return value in the variable named Result Private Sub btnDemo_Click(. . .) _ Handles btnDemo.Click Dim Result As Double Result = Square(34.55) End Sub
Execution flow of a Function procedure call
Common Function Procedure Errors Procedures must be called with the correct number of arguments having the correct data types Arguments must be ordered correctly Standard widening type coercion rules apply More restrictive types will be implicitly converted to less restrictive types
Introduction to Applications with Multiple Modules Applications can contain multiple forms, Module blocks, and Class blocks Each form, Module, and Class appears in the Solution Explorer A physical file can contain multiple Module and Class blocks Physical module files have a suffix of .vb.
Figure 6-4: The Solution Explorer containing multiple files
Adding a Form Module to an Application Use the Add New Item dialog box Click Project, Add New Item The Add New Item dialog box templates might vary Select the form type to add from the available templates The new form appears in the Solution Explorer
Add New Item dialog box
Setting the Startup Object A Windows Application project can have two possible entry points A procedure named Main in a Module block A form in the application Set the startup object using the Project property page (Application tab)
Project property page
Operations on Forms Form instances must be created Forms must be displayed Visible forms can be hidden or closed Form events can be handled
Creating and Displaying Multiple Form Instances Visual Basic supplies a default form instance having the same name as the form The form instance is created implicitly, as necessary Example – referencing a form frmAbout.Text = "About Form"
Displaying Forms Once created, a form must be displayed A form can be displayed in two ways As a modal form Modal forms must be hidden or closed before the parent form can be displayed Display by calling the ShowDialog method As a non-modal form The end user can change input focus between non-modal forms at will Display by calling the Show method
Displaying Forms (example) Display a form as a modal dialog box frmAbout.ShowDialog() Display a form as a non-modal dialog box frmAbout.Show()
Hiding and Closing a Form A form can be hidden The objects for a hidden form still exist Call the Hide method to hide a form The Visible property is set to False A form can be closed The objects for a closed form are destroyed Call the Close method to close a form Me.Close()
Introduction to Form Events Events fire as a form gets focus and loses focus Activated event fires each time a form gets focus Deactivate event fires each time a form loses focus Load event fires when a form is loaded into memory Load does not fire for a hidden form FormClosing event fires just before a form is unloaded from memory After a form has closed, the FormClosed event fires
Figure 6-7: Order of form events
Communicating Data Between Forms Public variables can be shared between forms (modules) and other assemblies Friend variables can be shared between forms and modules in the current assembly Private variables can only be used by the module containing the declaration (Class or Module block)
Procedures and Access Modifiers Access modifiers control the visibility of procedures A Private procedure can only be called from the module containing the procedure declaration Procedures declared with the Public and Friend access modifiers can be called by other modules and classes
Control Instances and Friend Data By default, control instances are declared with the Friend access modifier Thus, they can be referenced by other forms in an application Example: Friend txtUserName As _ System.Windows.Forms.TextBox Friend txtUserID As _
Controlling accessibility with the Private and Friend access modifiers
The Accessibility of Public Data Public data is globally accessible to all procedures in an assembly and by other assemblies Example: Public Class frmUser Public GlobalVariable As Integer End Class
Introduction to Custom Classes Custom classes can be created in addition to those supported by the .NET Framework class library Custom classes can be reused by other applications Class elements: Classes typically have methods Classes typically have properties A class has a constructor Classes may have events
Introduction to Class Design Encapsulation refers to the coupling of data and the processes that operate on that data Data should only be modified by procedures Classes have an interface and an implementation The interface consists of the exposed properties, methods, and events The interface is used by other developers The implementation forms the hidden part of the class The implementation is hidden from the developers using the class Each class should be designed to mimic a process or related group of processes
Introduction to UML Class Diagrams A class can be modeled using a UML class diagram A UML class diagram has three compartments divided by horizontal lines Top compartment contains the class name Middle compartment contains the attributes (properties) Lower compartment contains the operations (methods)
UML class diagram
UML Class Diagram (analysis) Plus and minus signs denote whether the attribute or operation is public (+) or private (-) Arguments appear in the declaration in indicates an input argument The data type of a method's return value also appears following a full colon (:)
Implementing Classes Create methods using Function and Sub procedures with the Public access modifier Create properties with Public fields or Property procedures Constructors are created using a Sub procedure named New Declare hidden members with the Private access modifier
Creating Methods Classes have a name, attributes, and operations Operations are called methods Methods are created with Public Function or Sub procedures Private procedures are part of the implementation and are not methods (part of the interface)
Creating Methods (example) Create methods named MakeWithdrawal and Make Deposit to decrease and increase the account balance Public Class BankAccount Private HiddenAccountBalance As Double Public Function MakeWithdrawal( _ ByVal amount As Double) As Double HiddenAccountBalance = _ HiddenAccountBalance - amount Return HiddenAccountBalance End Sub Public Function MakeDeposit( _ HiddenAccountBalance + amount End Class
Introduction to Property Procedures Public and Friend variables violate encapsulation rules It's possible to access class data directly Data should only be modified by a procedure Property procedures are used to implement properties Property procedures do not violate encapsulation rules Property procedures are similar to Function and Sub procedures
Property Procedures (syntax) [ReadOnly | WriteOnly | Property] varName ([parameterList]) [As type] [Get [statements] [End Get] [Set(ByVal value As type) End Set] End Property
Property Procedures (syntax dissection) Read-only properties are declared with the ReadOnly keyword Write-only properties are declared with the WriteOnly keyword varName contains the property name parameterList contains the parameters (arguments) passed to the property As type clause defines the data type of the property Statements in the Get block execute when the property's value is read Statements in the Set block execute when the property's value is written
Property Procedures (example) Declare a Property procedure named AccountName Private HiddenAccountName As String Public Property AccountName() As String Get Return HiddenAccountName End Get Set(ByVal value As String) HiddenAccountName = value End Set End Property
Executing Property procedures
Creating Read-only Properties Add the ReadOnly keyword to the property declaration Omit the Set block Including the Set block will cause a syntax error
Creating Read-Only Properties (example) Create a read-only property named GetAccountBalance Public ReadOnly Property GetAccountBalance() _ As Double Get Return HiddenAccountBalance End Get End Property
Creating Write-only Properties Add the WriteOnly keyword to the property declaration Omit the Get block Including the Get block will cause a syntax error
Introduction to Constructors Visual basic classes can have an optional constructor A constructor is a Sub procedure named New The constructor is called automatically when a class instance is created Constructors can accept 0, 1, or many arguments
Constructor (example 1) A constructor without arguments Public Class BankAccount Private HiddenDateCreated As DateTime Public Sub New() HiddenDateCreated = Now End Sub End Class
Constructor (example 2) A constructor with arguments Public Class BankAccount Private HiddenDateCreated As DateTime Private HiddenAccountNumber As Integer Public Sub New(argAccountNumber As Integer) HiddenDateCreated = Now HiddenAccountNumber = argAccountNumber End Sub End Class
Calling a constructor
Understanding Shared Data and Procedures One copy of shared data exists for all classes and modules Variables in a Module block are always shared One copy of instance data exists for each class instance Variables in a Class block are shared when declared with the Shared keyword
Chapter Summary Procedures are categorized as Function or Sub procedures Function procedures return a value Sub procedures to not Most applications are made up of multiple forms and modules Use the Add New Item dialog box to add a form or module to a project The startup object is a form or a procedure named Main appearing in a Module block
Chapter Summary (continued) Display forms as a modal dialog box by calling the ShowDialog method Display forms as a non-modal dialog box by calling the Show method Events fire as a form opens and closes and gets and loses input focus Access modifiers (Public, Private, Friend) control the visibility of a procedure or variable Classes are modeled with UML class diagrams
Chapter summary (continued) Create Public Function and Sub procedures to create methods Create Property procedures to define a property A Sub procedure named New is the constructor Class data can be shared data or instance data