Home > Articles > Programming > Visual Basic

This chapter is from the book

This chapter is from the book

Defining Methods

The methods of a class define the behavior and functionality associated with the class. Methods are implemented as subroutines and functions. For example, a Product class has Create and Save methods.

This section details the process of creating a method. It then covers some additional techniques for defining methods.

Creating a Method

Methods define the logic in your application. Create a method in a class for each set of business logic identified for the class during the design phase.

Implement a method using a subroutine when the method does not need to return a value, or a function if the method does need to return a value.

To define a method:

  1. Open the class in the Code Editor.
  2. Create the subroutine or function for the method.

    For example:

    Public Function Create
    

    Use good naming conventions for your method name. The recommended convention is to use the method's human-readable name, concatenating the words and using Pascal case, whereby each word in the name is capitalized.

    The purpose of this particular method is to create an instance of the business object class using the Factory pattern, so it was named Create. Some developers don't like to use that name because it could imply that a new item, such as a new product, is being created when instead an instance is created for an existing item. Alternatively, you could name this method CreateInstance or GetProduct or simply Retrieve.

  3. Add the parameters appropriate for the method.

    For example:

    Public Function Create(ByVal prodID As Integer)
    

    Parameters define the data that is passed into or out of the function or subroutine. The number, name, and type of the parameters depend on the data that needs to be passed. In this example, the product ID is passed in to create an object populated with data for the defined ID.

    Use good naming conventions for your parameter names. The recommended standard is to use a logical parameter name, concatenating the words and using camel case, whereby the first letter is lowercase and the beginning of every other word is capitalized.

    Be sure that the parameter names do not conflict with any of your property names.

  4. If you are defining a function, define the method's return type.

    For example:

    Public Function Create(ByVal prodID As Integer) _
                                             As Product
    

    The return type depends on the data that needs to be passed back from the function. In this example, the return type is an instance of the Product class.

  5. Press the Enter key to automatically generate the method's remaining structure:

    Public Function Create(ByVal prodID As Integer) _
                                             As Product
    End Function
    
  6. Add code within the method to perform the desired operation.
  7. If you're implementing a Function, use the Return statement to return the value.

The purpose of this particular Create method is to create an instance of the class. As discussed earlier in this chapter, objects are often created from a class using the Factory pattern. The Create method is then used, instead of the constructor, to create instances of the class.

A Create method used to create an instance of a class would look similar to this:

Public Function Create(ByVal prodID As Integer) As Product
    Dim prod As Product
    'Create a new instance
    prod = New Product()

    'Populate the object
    If prodID = 1 Then
        prod.ProductID = 1
        prod.ProductName = "Mithril Coat"
        prod.InventoryDate = #4/1/2006#
    End If

    Return prod
End Function

The first line of this function declares an object variable. The New keyword is then used to create a new instance of the Product class. The object properties are then populated. Notice that these are hard-coded in this case. The property values will be assigned from data in a database in Chapter 8. For now, the values are hard-coded so that the Create method works at this point without needing the data access layer in place just yet. The last line of the function returns the instantiated and populated Product object.

Although these steps demonstrate a Create method, you can create any type of method using these steps. Alternatively, you can use the Class Designer, as described in the next chapter, to assist you in defining the methods of your class.

Use methods to perform all of the processing required by your application. To create good methods, ensure that each method has a single purpose and that the method is no longer than about one page. If a method is long, break it into multiple methods. This makes each method much easier to build and maintain.

Passing Parameters

Parameters to methods are passed either ByVal or ByRef. ByVal is short for "by value" and means that the parameter value is evaluated and then its value is passed to the method. ByRef is short for "by reference" and means that a reference to the parameter is passed to the method.

If you don't specify the passing mechanism, the default is ByVal. In most cases, you want to pass your parameters by value.

The only time you need to use ByRef is when you want to modify the parameter within the method and allow the calling code to receive the modified value upon return from the method call. ByRef can also be used to return parameters from the method if you need more than one return value.

For example, a ProcessRequest method needs to return the number of items processed and a response string to the calling code. The method signature uses the ByRef keyword as follows:

Private Function ProcessRequest(ByVal requestType As String, _
    ByRef requestResponse As String) As Integer
     Dim itemsProcessed As Integer = 0

     'Code that performs the request

     requestResponse = "Test Reply"
     Return itemsProcessed
End Function

This function is called as follows:

Dim requestCount As Integer
Dim response As String
requestCount = ProcessRequest("Test", response)
Debug.WriteLine(requestCount.toString & " " & response)
                                            ' Displays 0 Test Reply

If the requestResponse parameter was declared using the ByVal keyword, the response variable would always return Nothing, because it would not pass back the changed value from the function. By using the ByRef keyword, the response variable is set to the changed value.

Documenting the Method

It is always a good idea to add documentation for a method immediately after creating the method. You may even want to add the documentation just after defining the method signature and before you write the code within the method. By adding the documentation right away, you focus on the method's purpose, which helps you keep the method encapsulated. It is also much easier to document each method as you go along instead of facing the large task of going back later and documenting all the methods.

To document the method:

  1. Open the class in the Code Editor.
  2. Move the insertion point immediately before the word Public in the Public Function or Public Sub statement.
  3. Type three comment markers, defined in Visual Basic as apostrophes ('''), and press the Enter key.

    The XML comments feature automatically creates the structure of your method documentation as follows:

    ''' <summary>
    '''
    ''' </summary>
    ''' <param name="prodID"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    

    Notice how this automatically generates a param tag with the name of each method parameter.

  4. Type a summary of the method between the summary tags, the parameter descriptions between the param tags, and so on. Your documentation may be similar to this:
    ''' <summary>
    ''' Creates a populated instance of this class
    ''' </summary>
    ''' <param name="prodID">ID of the product to
    ''' create</param>
    ''' <returns>Instance of the Product class</returns>
    ''' <remarks></remarks>
    

Use the summary tags to describe the method's purpose and the param tags to define each parameter. The summary and param are the most important tags because they are used by Visual Studio.

When you provide method documentation using XML comments, your method displays documentation about itself in appropriate places within Visual Studio. For example, the documentation appears in the Intellisense List Members box when you type the object variable name and a period (.).

Using XML comments to document your methods makes it easier for you and other developers to work with your methods.

Overloading Methods

There may be times when you want to have different sets of parameters for a method. For example, you may want your Create method to accept an ID or string name. Or you may want a Retrieve method to work with no parameters to retrieve all the data or an ID to retrieve data for a particular ID.

You could define different method names to support different signatures, but a better way is to use overloaded methods. An overloaded method is a method that has the same name as another method but different parameters.

For example, the Create method defined in this section has a parameter for a product ID. If you want to allow creating objects by name as well, you could define an overloaded Create method as follows:

Public Function Create(ByVal prodName As String) As Product
    Dim prod As Product

    'Create a new instance
    prod = New Product()

    'Populate the object
    '...

    Return prod
End Function

A method can have any number of overloads, each with different sets of parameters. The parameters are evaluated based on the number and type of parameters, not the parameter names. So if you defined a Create method with a product name string parameter, you could not add a Create method with a description string parameter. This is because when you call the function and pass a string, the .NET runtime would not be able to tell which Create method you want to execute. Each overload must have a unique set of parameters.

Overloading is also great for enhancing your methods. For example, suppose you originally created a Create method with one parameter. You then need to add a withComments parameter to define whether to populate comment information. If code in your application calls the original Create method you don't want to break that code by adding a new parameter. Instead, you can create an overload for the Create method with the new parameter without needing to modify any existing code that calls the original method:

Public Function Create(ByVal prodName As String, _
    ByVal withComments As Boolean) As Product
     Dim prod As Product

     'Create a new instance
     prod = New Product()

     'Populate the object
     '...

     If withComments Then
         'also populate the comments
     End If

     Return prod
End Function

In many cases, the code you need to execute in each of the overloaded methods is similar. So a common technique is to have one overload call the other. So the Create method from the prior code example could be changed to the following:

Public Function Create(ByVal prodName As String) As Product
    Return Create(prodName, False)
End Function

The overload with one parameter simply calls the other overload, passing a default value for the withComments flag. In most cases, the majority of the code is in the overload with the most parameters.

Each overload appears in the Intellisense Parameter Info, as shown in Figure 5.2.

Figure 5.2

Figure 5.2 The 1 of 3 advises you that this method has three overloads. Use the up and down arrows to show the Parameter Info for each overloaded method.

Use overloading any time you want to define methods with the same name but different method signatures. Be sure that the signatures differ in the number or type of parameters.

Defining Shared Methods

Shared methods, sometimes called static methods, are methods that are shared between all the instances of a class. They do not require that you create an object before calling the method.

For example, if you want to display something to the debug window, you don't first create an instance of the Debug class and then use an object variable to call the WriteLine method. Instead, you call the WriteLine method directly for the class itself. The WriteLine method is a shared method.

You define shared methods in your classes using the Shared keyword on the method signature. For example:

Public Shared Function Create(ByVal prodID As Integer) As Product
    ...
End Function

When a method is shared, you no longer need to create an object from the class before using the method. So instead of using code that looks like this:

Dim prod as Product
prod = New Product
prod = prod.Create(1)

the code instead looks like this:

Dim prod as Product
prod = Product.Create(1)

Notice that the code does not create an instance and uses the class name (Product in this example) instead of the object variable name (prod) to call the method. This is because a shared method cannot be accessed using an instance.

The most common use of shared methods is for Factory pattern methods, as shown in the Create method example, and for function libraries. The .NET Framework makes extensive use of shared methods in its function libraries, such as the WriteLine method in the Debug class.

You can also use the Shared keyword on properties to share a property across all instances. This is useful for properties such as a count that needs to be aware of all instances.

When defining a shared property or method, keep the following in mind:

  • A shared property or method cannot reference nonshared properties.

    In the Create method example, the shared method created an instance of the class and used that instance to reference the properties. It cannot access the properties without an instance, because those properties are not shared. The properties are unique for each instance.

  • A shared property or method cannot reference a nonshared method of the class.

    If you need to call a nonshared property or method of the class within the shared property or method, you can create an instance of the class and use that instance to call the nonshared property or method.

  • Me is not valid within a shared property or method.

    Me references the current running instance, and a shared property or method does not have an instance.

Use the Shared keyword any time you want to define a property or method that is shared across all instances of your class. Access shared properties and methods using the class name instead of an instance variable.

Obsolescing Methods

Code changes over time. Methods that you created today may no longer be needed tomorrow. But if you delete them, every piece of code that calls the method needs to be changed. Depending on the features you are implementing, this may be necessary. But in many cases, you can define a smoother obsolescence plan.

Obsolescence is the concept in which methods become obsolete over time. Instead of changing a method for a new feature, you add a method overload to support the new feature, essentially making the original method obsolete. That way, you need to change only the code required for the new feature, not every piece of code that calls the original method. You can then obsolete the original method so that you don't forget to remove it at a later point in time.

In looking at the Create method example from earlier in this chapter, you defined the method with a product name parameter. Suppose you later find that you need to sometimes manage comment information. So you add an overloaded method with a flag defining whether to handle comment information. You want every call to the method to ultimately call the new method signature. But in the interim, by having the original method remain in place, any unchanged code still works.

To identify a method as obsolete, use the Obsolete attribute. An attribute is metadata that you can associate with programming elements such as classes, properties, and methods. Attributes are defined in Visual Basic using less-than (<) and greater-than (>) signs. Attributes must be defined on the same line as the declaration of the class, property, or method to which the attribute is assigned. Use the line-continuation character (_) to separate the attribute from the declaration so that they are easier to read.

For example, to define one overload of the Create method as obsolete, add the Obsolete attribute to the method:

<ObsoleteAttribute( _
  "Use the Create(prodName, withComments) instead", False)> _
Public Shared Function Create(ByVal prodName) As Product
    Return Create(prodID, False)
End Function

The attribute's name can be defined with or without the "Attribute" suffix; either Obsolete or ObsoleteAttribute can be used. Your coding standards may define that the suffix is included for clarity or not included for brevity. Either way, be consistent with all attributes.

Some attributes, such as the Obsolete attribute, have parameters. The first parameter in this case is a message to any developer using your obsolete method, and the second parameter is an error flag. This message appears in the Error List window (see Figure 5.3) as a warning if the second parameter is False, or as an error if the second parameter is True. This gives the developer using the method a warning or error, depending on your standard method obsolescence path.

Figure 5.3

Figure 5.3 When you define a property or method as obsolete, any developer using the method knows that the property or method is on the obsolescence path.

Define a standard obsolescence plan for your application. This plan defines when properties and methods are made obsolete, how long they should be obsolete in a warning mode, and at what point they should be marked with a compile-time error. This provides a phased approach to modifying your application.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020