Properties of an Application's Business Logic Layer

In this fourth part of a six-part series on building the business logic layer of a .NET application, we focus on the layer's properties. This article is excerpted from chapter five of the book Doing Objects in Visual Basic 2005, written by Deborah Kurata (Addison-Wesley, 2008; ISBN: 0321320492).

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
December 30, 2009
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Documenting the Property

It is always a good idea to add documentation for a property immediately after defining the property. By adding the documentation right away, you have it in place so that you can use the documentation as you build the remainder of the application.

To document the property:

  1. Open the class in the Code Editor. 
     
  2. Move the insertion point immediately before the word Public in the Public Property 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 property documentation as follows:

    ''' <summary>
    '''
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>





    NOTE: If you type the three comment markers in the empty line above the property definition instead of on the same line as the property definition, you don’t need to press the Enter key to generate the documentation structure. 



  4. Type a summary of the property between the summary tags, the value of the property between the value tags, and so on.

    Your documentation may be similar to this:

    ''' <summary>
    ''' Gets or sets the product name
    ''' </summary>
    ''' <value>Product Name</value>
    ''' <returns>Product Name</returns>
    ''' <remarks></remarks>

Use the summary tags to describe the purpose of the Property statement. By convention, a Property statement summary begins with the text “Gets or sets the...” for a read-and-write property, “Gets the...” for read-only properties, and “Sets the...” for write-only properties.

In this example, the value and returns tags don’t provide very useful information, because the product name is self-explanatory. These two tags could be deleted in this case. However, in other cases the property may not be as obvious, so the documentation defined in the XML tags is more useful. For example, a Status property is not as obvious, and the XML documentation could provide further information, such as what the status value means and what it actually returns.

When you provide a summary of a property using XML comments, the summary appears in appropriate places within Visual Studio. For example, the summary appears in the Intellisense List Members box when you type the object variable name and a period (.).

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


Building Along

For the Purchase Tracker sample application:

  • Open the Product class in the Code Editor.
  • Add documentation for the ProductName property using XML comments.

In the Code Editor, view the comment by typing prod. in the Load event in the ProductWin form.

When you type the period (.), Visual Studio displays the Intellisense List Members box, showing all the properties and methods for the class. Click the
ProductName property to see the XML comments. Be sure to remove this code; otherwise, the project will have a syntax error.


Defining Property Accessibility

In most cases, properties are public. The primary purpose of properties is to provide public access to the data relating to a particular object. But in some cases, you may want the property to be read-only and, in rare cases, write-only. You can define a property’s accessibility using additional keywords in the Property statement.

Some fields should be changed only by code in the class, not by any code outside the class. For example, a ProductID should not be changed by code outside the class, because the ID is the key property used to identify the product. It should be set only when the product is created and then never changed. (See Chapter 8 for more information on primary key fields.)

You can define a property to be read-only using the ReadOnly keyword. If you need to define a property as write-only, you can use the WriteOnly keyword.

Public ReadOnly Property ProductID() As Integer
    Get

    End Get
End Property

When you make the property read-only or write-only using the keyword, the code in the class cannot access the property either. If the property is read-only, the code in the class must access the private backing variable to update the value. It would be better to define the accessibility on the accessors so that the getter could be public but the setter could be private. This would allow the code in the class to set the property but make it appear read-only outside this class.

To define separate accessibility on the accessors, add an accessibility keyword to either the getter or setter:

Public Property ProductID() As Integer
    Get

    End Get
    Private Set(ByVal value As Integer)

    End Set
End Property

Notice the Private keyword on the setter. This allows the getter to be public but restricts the setter to be private. The code within the class can then get or set the property, and code outside the class can only get the property.

Some restrictions and rules apply when you use accessibility on the accessors:

  1. The accessibility on the Property statement must be less restrictive than the accessibility on the accessor.

    For example, you cannot define the Property statement to be private and then make the getter public.
  2. You can add accessibility to the getter or setter, but not both. If the getter needs to be friend and the setter needs to be private, for example, make the Property statement friend (the least restrictive), and make the setter private. 
     
  3. If you use the ReadOnly or WriteOnly keywords, you cannot add accessibility on the accessor.

Define accessibility appropriately to ensure that your properties are accessed only as they should be. Most properties are public, but for some properties, such as IDs, define private setters to allow reading but not setting of the property.  


 Building Along

For the Purchase Tracker sample application:

  • Open the Product class in the Code Editor.
  • Add a ProductID property with a private setter, as defined in this section.
  • Add code to declare a backing variable, and get and set its value in the property.
  • Add documentation for the ProductID property using XML comments. This new property is used later in this chapter.

Handling Nulls

A data type is said to be nullable if it can be assigned a value or a null reference. Reference types, such as strings and class types, are nullable; they can be set to a null reference, and the result is a null value. Value types, such as integers, Booleans, and dates, are not nullable. If you set a value type to a null reference, the result is a default value, such as 0 or false. A value type can express only the values appropriate to its type; there is no easy way for a value type to understand that it is null.

The .NET Framework 2.0 introduces a Nullable class and an associated Nullable structure. The Nullable structure includes the value type itself and a field identifying whether the value is null. A variable of a Nullable type can represent all the values of the underlying type, plus an additional null value. The Nullable structure supports only value types because reference types are nullable by design.

For example, say you have a Product class with a ProductID property defined as an integer, a ProductName property defined as a string, and an InventoryDate property defined as a date. The following code sets each property to Nothing to assign a null reference:

Dim prod as Product
prod = New Product
prod.ProductID = Nothing
prod.ProductName = Nothing prod.InventoryDate = Nothing

Debug.WriteLine(prod.ProductID)   ' Displays 0
Debug.WriteLine(prod.ProductName) ' Displays (Nothing)
Debug.WriteLine(prod.InventoryDate)
                                 
' Displays 1/1/0001 12:00:00 AM

If you view these values, they are 0, Nothing, and 1/1/0001 12:00:00 AM, respectively. The ProductID and InventoryDate properties are value types and therefore cannot store a null. Instead, they store a default value when they are assigned a null reference.

There may be cases, however, when you need your code to really handle a null as a null and not as a default value. It would be odd, for example, to handle a null date by hard-coding a check for the 1/1/0001 date.

To make a value type property nullable, you need to declare it using the Nullable structure. However, you still want your property to be strongly typed as an integer, date, Boolean, or the appropriate underlying type. The ability to use a class or structure for only a specific type of data is the purpose of generics.

Generics allow you to tailor a class, structure, method, or interface to a specific data type. So you can create a class, structure, method, or interface with generalized code. When you use it, you define that it can work only on a particular data type. This gives you greater code reusability and type safety.


NOTE: A number of generic collection classes are also provided in the .NET Framework. These are great for creating collections of objects in which only a particular type of object can be in the collection. (See the next chapter for more information on generic collections.) You can use the generic types defined in the .NET Framework or create your own.


The .NET Framework built-in Nullable structure is generic. When you use the structure, you define the particular data type to use.

As a specific example, an InventoryDate property that allows the date to be a date or a null value uses the generic Nullable structure as follows:

Private _InventoryDate As Nullable(Of Date) Public Property InventoryDate() As Nullable(Of Date)
    Get
       
Return _InventoryDate
    End Get
    Set(ByVal value As Nullable(Of Date))
        _InventoryDate = value
    End Set
End Property

Notice the syntax of the Nullable structure. Since it supports generics, it has the standard (Of T) syntax, where T is the specific data type you want it to accept. In this case, the Nullable structure supports dates, so the (Of Date) syntax is used. This ensures that the Nullable structure contains only a date or a null value.

You can then use this property in your application as needed. For example:

Dim prod as Product
prod = New Product
If prod.InventoryDate.HasValue Then
    If prod.InventoryDate.Value < Now.Date.AddDays(-10) Then
        MessageBox.Show("Need to do an inventory")
    End If
Else
    MessageBox.Show("Need to do an inventory -never been done")
End If

The HasValue property of the Nullable class defines whether the value type has a value—in other words, whether it is null. If it does have a value, you can retrieve the value using the Value property of the Nullable class.


NOTE: The Nullable type does not support the compare (=) operator. So you cannot use code such as:

If prod.InventoryDate = Nothing Then

You must instead use the HasValue and Value properties, as shown in the preceding code example.


The Nullable structure is exceptionally useful when you’re working with databases, because empty fields in a database are often null. Assuming that you have an InventoryDate field in a table, you could write code as follows:

If dt.Rows(0).Item("InventoryDate") Is DBNull.Value Then
    prod.InventoryDate = Nothing
Else
    prod.InventoryDate = _
          CType(dt.Rows(0).Item("InventoryDate"), Date)
End If

The If statement is required here because you cannot convert a DBNull to a date using CType. So you first need to ensure that it is not a null.

Use the Nullable structure any time you need to support nulls in a value type, such as an integer, Boolean, or date.


Building Along

For the Purchase Tracker sample application:

  1. Open the Product class in the Code Editor.
  2. Add the InventoryDate property, as defined in this section. 
     
  3. Add code to declare a backing variable, and get and set its value in the property, as defined in this section. 
     
  4. Add documentation for the InventoryDate property using XML comments. 
     
  5. Open the ProductWin form in the Code Editor. 
     
  6. In the Load event for the ProductWin form, add code to set and then display the InventoryDate property:

    Dim prod as Product
    prod = New Product
    prod.InventoryDate = Now() Debug.WriteLine(prod.InventoryDate)
           ' Displays 9/25/2006 1:45:53 PM

Run the application. It displays your splash screen and then shows the MDI parent form. Select Products | Manage Products to display the ProductWin form. The debug message appears in the Immediate window (Debug | Windows | Immediate) or in the Output window (Debug | Windows | Output), depending on your settings.


By adding properties to your classes, you provide your application with easy access to object data. This allows the user interface, for example, to display and update the data.


Stateful Versus Stateless Classes

For some developers, myself included, it may seem unnatural at first to have properties defined for your business objects. Until recently, the best practice for Web applications and large-scale systems was to keep your business objects stateless so that they did not retain any property values between calls. The business objects consisted of only methods. Any data needed by those methods was passed in as parameters.

Stateful classes were deemed inappropriate for Web applications because there was no efficient way to maintain the values of the properties between calls to a page.

Stateful classes were deemed inefficient for large-scale systems with application servers because each time the user interface requested a property from the business object, a network hit was required to retrieve the data from the application server and pass it down. These were called “chatty” calls.

With the simplicity of deployment, all application components are now often deployed to the user’s system, reducing the need for application servers. And many features have been added to simplify Web state management.

With many of the new features of .NET and today’s architectural practices, it now makes sense to build stateful business objects. This opens the door for building objects that can easily support object binding.


Please check back tomorrow for the continuation of this series.

blog comments powered by Disqus
.NET ARTICLES

- .Net 4.5 Brings Changes
- Understanding Events in VB.NET
- Objects, Properties, Events and Methods in V...
- Install Visual Web Developer Express 2010
- Microsoft Gadgeteer an Open Source Alternati...
- Best DotNetNuke Modules
- Facebook Image Viewer in Visual Basic
- Murach`s ADO.NET 4 Database Programming with...
- 5 Must Have Visual Studio 2010 Extensions
- Dynamic Web Applications with ASP.NET Mono u...
- PDFSharp: HTML to PDF in ASP.NET 3.5 using V...
- Using the PDFSharp Library in ASP.NET 3.5 wi...
- Sending Email in ASP.NET 3.5 using VB.NET wi...
- ASP.NET 3.5 Role Based Security and User Aut...
- Creating ASP.NET Login Web Pages and Basic C...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials