Chapter 2 Building Multitier Programs with Classes McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved.
Objectives Discuss object-oriented terminology Create your own class and instantiate objects based on the class Create a new class based on an existing class Divide an application into multiple tiers Throw and catch exceptions Choose the proper scope for variables Validate user input using the TryParse and display messages using an ErrorProvider component McGraw-Hill 2-2
Object-Oriented Programming A key concept of OOP is using building blocks, or classes In VB everything is based on classes Each form is a class and must be instantiated before it can be used Variables of the basic data types are objects, with properties and methods McGraw-Hill 2-3
OOP Terminology Key features of object-oriented programming Abstraction Encapsulation Inheritance Polymorphism McGraw-Hill 2-4
Abstraction Abstraction means to create a model of an object for the purpose of determining the properties and methods of the object For example, a Customer class is an abstract representation of a real customer Think of objects generically What are the characteristics of a typical product Not what are the characteristics of a specific product McGraw-Hill 2-5
Encapsulation Combination of characteristics of an object along with its behaviors One package holds the definition of all properties, methods, and events Makes data hiding possible Properties and methods are hidden Public and Private keywords expose only those properties and methods that need to be seen by the outside world Any Windows program is an example of encapsulation Form is a class Methods and events are enclosed within the Class and End Class statements Variables are properties of that specific form class McGraw-Hill 2-6
Inheritance - 1 The ability to create a new class from an existing class Add enhancements to a class without modifying the original The original class is called the base, superclass, or parent class The inherited class is called a subclass, a derived class, or a child class Inherited classes always have an is a relationship with the base class McGraw-Hill 2-7
Inheritance - 2 Place common code in a base class Create derived classes or subclasses to call the shared functions Create a class strictly for inheritance Called an abstract class Declared with MustInherit in the class header Cannot instantiate objects from an abstract class, only inherit new classes from it McGraw-Hill 2-8
Multiple subclasses can inherit from a single base class Inheritance - 3 McGraw-Hill 2-9
Polymorphism Ability to take on many shapes or forms Methods with identical names but different implementations, depending on the situation The Select method is different for radio buttons, check boxes, and list boxes A single class can have more than one method with the same name but a different argument list The method is said to be overloaded When an overloaded method is called, the argument type determines which version of the method to use McGraw-Hill 2-10
Reusable Objects Big advantage of OOP is the ability to reuse objects Class modules can be used in multiple projects Each object from the class has its own set of properties Developing applications is like building objects with Lego blocks The blocks fit together and can be used to build many different things McGraw-Hill 2-11
Multitier Applications - 1 Three-tier applications are popular Presentation (user interface) tier Business services tier Business logic or business rules may be written in multiple classes that can be stored and run from multiple locations Data tier Goal is to create components that can be combined and replaced McGraw-Hill 2-12
Multitier Applications - 2 McGraw-Hill 2-13
Designing Your Own Class Variables are characteristics or properties Methods are behaviors Sub procedures or function procedures McGraw-Hill 2-14
Creating Properties in a Class Declare all variables in a class as Private to accomplish encapsulation Private variable values are available only to procedures within the class When objects are created from a class, assign values to the properties Use special property procedures to Pass the values to the class module Return values from the class module McGraw-Hill 2-15
Property Procedures - 1 Property procedures allow a class to access its properties A Get retrieves a property value A Set assigns a value to a property Name Property procedures with a name that describes the property, such as LastName or EmployeeNumber McGraw-Hill 2-16
Property Procedures - 2 Set statement uses the Value keyword Refers to the incoming value for the property Property procedures are public by default Omit the option Public keyword Inside the procedure, assign a return value to the procedure name Or use a Return statement The data type of the incoming value for a Set must match the type of the corresponding Get McGraw-Hill 2-17
The Property Procedure General Form Private ClassVariable As DataType Declared at the module level. [Public] Property PropertyName() As DataType Get PropertyName = ClassVariable or Return ClassVariable End Get Set(ByVal Value As DataType) [statements, such as validation] ClassVariable = Value End Set End Property McGraw-Hill 2-18
The Property Procedure - Example Private LastNameString As String Declared at the module level. Public Property LastName() As String Get Return LastNameString Alternate version: LastName = LastNameString End Get Set(ByVal Value As String) LastNameString = Value End Set End Property McGraw-Hill 2-19
Read-Only and Write-Only Properties - 1 Use the ReadOnly modifier and write only the Get portion of a property procedure to create a read-only property Private paydecimal As Decimal Declared at the module level. Public ReadOnly Property Pay() As Decimal Make the property read-only. Get Return PayDecimal End Get End Property McGraw-Hill 2-20
Read-Only and Write-Only Properties - 2 Use the WriteOnly modifier and write only the Set portion of a property procedure to create a write-only property Private PasswordString As String Declared at the module level. Public WriteOnly Property Password() As String Make it write-only. Set (ByVal Value as String) PasswordString = Value End Set End Property McGraw-Hill 2-21
Constructors and Destructors A constructor is a method that automatically executes when a class is instantiated Create a constructor for a class by writing a Sub New procedure A destructor is a method that automatically executes when an object is destroyed Must be named Dispose and override the Dispose method of the base class McGraw-Hill 2-22
Overloading the Constructor - 1 Two methods that have the same name but a different list of arguments (the signature) are overloaded Create overloaded methods by giving the same name to multiple procedures Each has a different argument list McGraw-Hill 2-23
Overloading the Constructor - 2 Constructors in the Payroll class. Sub New() Constructor with empty argument list. End Sub Sub New(ByVal HoursInDecimal As Decimal, ByVal RateInDecimal As Decimal) Constructor that passes arguments. Assign incoming values to private variables. HoursDecimal = HoursInDecimal RateDecimal = RateInDecimal End Sub McGraw-Hill 2-24
A Parameterized Constructor A constructor that requires arguments Allows the passing of arguments/properties as the new object is created Instantiate new object in a Try/Catch block to catch missing or invalid input McGraw-Hill 2-25
Assigning Arguments to Properties Use property procedures to assign initial property values Within the class module, use the Me keyword to refer to the current class Improved constructor for the Payroll class. Sub New(ByVal HoursInDecimal As Decimal, ByVal rate Decimal AsDecimal) Assign arguments to properties. With Me.Hours = HoursInDecimal.Rate = RateInDecimal End With End Sub McGraw-Hill 2-26
A Basic Business Class Payroll application in two tiers Does not have a data tier as there is no database element McGraw-Hill 2-27
The Presentation Tier Also called the user interface Handles all communication with the user Results of calculations and any error messages to the user come from this tier Validation for numeric input handled in the form Business rules validation handled in the business services tier McGraw-Hill 2-28
The Business Services Tier Validation and calculations performed in the class, part of this tier McGraw-Hill 2-29
Throwing and Catching Exceptions The system throws an exception when an error occurs A program can catch the exception and take an action or ignore the exception Enclose any code that could cause an exception in a Try/Catch block McGraw-Hill 2-30
What Exception to Throw? Use existing.net Framework exception classes Create your own exception class that inherits from existing classes Use the System.ApplicationException class when you throw your own exceptions from application code Use the Throw statement in this format: Throw New ApplicationException( Error message to display. ) McGraw-Hill 2-31
Passing Additional Information in an Exception Constructor for the ApplicationException class takes only the error message as an argument Class has additional properties that can be set and checked For example, set the Source property and the Data property which can hold sets of key/value pairs McGraw-Hill 2-32
Throwing Exceptions Up a Level Show error messages to the user only in the user interface For a class that does not have a user interface Pass the exception up the next higher level which is the component that called the current code Use the Throw keyword to pass the exception to the form that invoked the class McGraw-Hill 2-33
Guidelines for Throwing Exceptions Always include an error message The message should be Descriptive Grammatically correct, in a complete sentence with punctuation at the end McGraw-Hill 2-34
Alternatives to Exception Handling Use exception handling for situations that are errors and out of the ordinary Use the TryParse method to help avoid parsing exceptions for invalid user input Bad input data is handled by the Else clause Dim HoursDecimal As Decimal Decimal.TryParse(HoursTextBox.Text, Hours Decimal) If HoursDecimal > 0 Then Passed the conversion; perform calculations. Else MessageBox.Show( Invalid data entered. ) End If McGraw-Hill 2-35
Modifying the User Interface to Validate at the Field Level Further improves the user interface Displays a message directly on the form, next to the field in error Use an ErrorProvider component for the message rather than a message box Perform field-level validation for numeric data in the Validating event of each text box McGraw-Hill 2-36
The Validating Event Order of events of the text box Enter GotFocus Leave Validating Validated LostFocus McGraw-Hill 2-37
Canceling the Validating Event CancelEventArgs argument of the Validating event handler cancels Validating event and returns focus to the control To not allow validation to cancel the form s closing, write an event handler for the form s FormClosing event e.cancel = False McGraw-Hill 2-38
Controlling Validating Events Suppress extra Validating events by temporarily turning off CausesValidation With.RateTextBox.SelectAll().CausesValidation = False.Focus().CausesValidation = True End With McGraw-Hill 2-39
The ErrorProvider Component Use an ErrorProvider component to make an error indicator appear next to the field in error Add the ErrorProvider at design time and set its properties in code If input data is invalid, a blinking icon next to the field in error can be displayed, along with a popup message Clear the ErrorProvider after the error is corrected McGraw-Hill 2-40
Modifying the Business Class Modify the business class Create a new class that inherits from the original class Add properties and methods to an existing class If any applications use the class, do not change the behavior of existing properties and methods McGraw-Hill 2-41
Instance Variables versus Shared Variables Instance Variables Each new instance of an object has its own values These properties are called instance properties, instance variables, or instance members Shared Variables Called shared properties, shared variables, or shared members Use to accumulate totals and counts for all instances of a class Private to the class, use public Get methods to make the properties accessible Retrieve shared properties by using the class name McGraw-Hill 2-42
Displaying the Summary Data To display a second form from the main form, declare an instance of the form s class and show the form Retrieve the summary values in a summary form from the shared properties of the business tier McGraw-Hill 2-43
Namespaces Used for grouping and referring to classes and structures A class or structure name must be unique in any one namespace Most classes in the.net Framework are in the System namespace Can declare namespaces in VB projects By default, each project namespace matches the project name McGraw-Hill 2-44
Scope Determine the scope by the location of the declaration and its accessibility modifier (Public or Private) Choices for scope, from widest to narrowest Namespace Module level Procedure level Block level McGraw-Hill 2-45
Namespace Any variable, constant, class, or structure declared with the Public modifier has namespace scope Declare classes and structures as Public, but not variables and constants Classes share variables only by using Property Set and Get procedures McGraw-Hill 2-46
Module Level Also called class-level scope A Private variable declared inside any class, structure, or module, but outside any sub procedure or function Declare module-level variables at the top of the class Variables can be declared anywhere inside the class, but outside of a procedure or function McGraw-Hill 2-47
Procedure Level Also called local scope Declare procedure level variables inside a procedure or function, but not within a block Can reference the variable anywhere inside the procedure but not in other procedures All procedure-level variables are private and declared with the Dim keyword Public keyword is not legal inside a procedure McGraw-Hill 2-48
Block Level - 1 A variable declared inside a code block Code blocks include: If/End If Do/Loop For/Next Select Case/End Select Try/Catch/Finally/End Try McGraw-Hill 2-49
Block Level - 2 Blocks that cause confusion are the Try/Catch/Finally/End Try The Try is one block Each Catch is a separate block The Finally is a separate block Cannot declare a variable in the Try and reference it in the Catch or the Finally blocks Declare an object variable at module or procedure level and instantiate the object inside the Try block McGraw-Hill 2-50
Lifetime The lifetime of a variable is as long as the variable remains in scope A namespace-level variable s lifetime is as long as the program is running A module-level variable s lifetime is as long as any reference to the class remains Generally as long as the program runs A procedure-level variable s lifetime is one execution of the procedure McGraw-Hill 2-51
Accessibility Domains McGraw-Hill 2-52
Creating Classes That Inherit Add a new class to the project Recommended approach Create a new file for each Public class Name the file the same name as the class name Exceptions are helper classes that will never be used by any other application Declare with the Friend keyword Used only in the current project McGraw-Hill 2-53
Adding a New Class File Select Project/Add Class Creates a new file with the.vb extension Add the Inherits clause on the first line following the Class declaration Add comments above the Class statement McGraw-Hill 2-54
Creating a Constructor A subclass must have its own constructor because constructors are not inherited If a constructor is not created, VS creates an implicit empty constructor First statement in a constructor of an inherited class should call the constructor of the base class MyBase.New() Pass arguments to a parameterized constructor in a base class McGraw-Hill 2-55
Inheriting Variables and Methods All public and protected variables and methods are inherited from the base class Constructors are not inherited McGraw-Hill 2-56
Shadowing and Overriding Methods An inherited class can have a method with the same name as a method in its base class The new method may shadow or override the base class method McGraw-Hill 2-57
Overriding To override a method in the base class, the method must be declared as overridable In the derived class the Overrides keyword must be used and it must have the same accessibility as the base class Write separate methods to override each version/signature of the base-class method McGraw-Hill 2-58
Shadowing A method in a derived class can shadow a method in the base class The new method replaces the base-class method in the derived class Does not replace it in any new classes derived from that class Shadowing hides all signatures with the same name in the base class McGraw-Hill 2-59
Using Properties and Methods of the Base Class Any public property or method of the base class can be referenced from the subclass If the base-class method has not been overridden or shadowed in the subclass, the method can be called directly Call a function in the base class by including the MyBase keyword Use the Me keyword to refer to a property or method of the current class McGraw-Hill 2-60
Passing Control Properties to a Component Convert a text box value to integer Integer.Parse(QuantityTextBox.Text) Pass the Checked property of a check box to a Boolean property Create an enumeration for the available choices of a radio button group or a list box McGraw-Hill 2-61
Creating an Enumeration Sets up a list of choices for a property VB compiler substitutes the numeric value of the element Enum is a list of named constants Data type must be integer, short, long, or byte McGraw-Hill 2-62
Garbage Collection The process of destroying unused objects and reclaiming memory Allow variables to go out of scope when you are finished with them The garbage collector runs periodically and destroys objects and variables that have no active reference McGraw-Hill 2-63