Home > Articles > Programming > Visual Basic

  • Print
  • + Share This
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.

  • + Share This
  • 🔖 Save To Your Account