Section 4.8. Validating Data with Set Accessors in Properties


4.8. Validating Data with Set Accessors in Properties

In Section 4.5, we introduced properties whose Set accessors allow clients of a class to modify the value of a Private instance variable. In Fig. 4.7, class GradeBook defines property CourseName's Set accessor to assign the value received in its parameter value to instance variable courseNameValue (line 14). This CourseName property does not ensure that courseNameValue contains valid data. In this section, we enhance our property to include data validation in its Set accessor. Property CourseName (Fig. 4.12) does not ensure that the course name adheres to any particular format or follows any other rules regarding what a "valid" course name is. Suppose that a university can display student transcripts in an online form that can hold course names of only 25 or fewer characters. If the university uses a system containing GradeBook objects to generate the transcripts, we might want class GradeBook to ensure that its courseNameValue never contains more than 25 characters. The program of Figs. 4.154.16 enhances class GradeBook's property CourseName to perform this validation.

Figure 4.15. Method declarations for class GradeBook with a CourseName property that validates the length of instance variable courseNameValue.

  1  ' Fig. 4.15: GradeBook.vb  2  ' GradeBook class with a property that performs validation.  3  Public Class GradeBook  4     Private courseNameValue As String ' course name for this GradeBook  5  6     ' constructor initializes CourseName with String supplied as argument  7     Public Sub New (ByVal name As String)  8        CourseName = name ' validate and store course name  9     End Sub ' New 10 11     ' property that gets and sets the course name; the Set accessor 12     ' ensures that the course name has at most 25 characters 13     Public Property CourseName() As String 14        Get ' retrieve courseNameValue 15           Return courseNameValue 16        End Get 17 18        Set(ByVal value As String) ' set courseNameValue                        19           If value.Length <= 25 Then ' if value has 25 or fewer characters     20              courseNameValue = value ' store the course name in the object     21           End If                                                               22         23           If value.Length > 25 Then ' if value has more than 25 characters     24              ' set courseNameValue to first 25 characters of value             25              ' start at 0, length of 25                                        26              courseNameValue = value.Substring(0 , 25)                          27         28              Console.WriteLine( _                                              29                 "Name """ & value & """ exceeds maximum length (25).")         30              Console.WriteLine( _                                              31                 "Limiting course name to first 25 characters." & vbCrLf)       32           End If                                                               33        End Set                                                                 34     End Property ' CourseName 35 36     ' display a welcome message to the GradeBook user 37     Public Sub DisplayMessage() 38        ' this statement uses property CourseName to get the 39        ' name of the course this GradeBook represents 40        Console.WriteLine("Welcome to the grade book for " _ 41            & vbCrLf & CourseName & "!") 42     End Sub ' DisplayMessage 43  End Class ' GradeBook 

Figure 4.16. Creating and manipulating a GradeBook object in which the course name is limited to 25 characters in length.

  1  ' Fig. 4.16: GradeBookTest.vb  2  ' Create and manipulate a GradeBook object; illustrate validation.  3  Module GradeBookTest  4     ' Main begins program execution  5     Sub Main()  6        ' create two GradeBook objects;  7        ' initial course name of gradeBook1 is too long  8        Dim gradeBook1 As New GradeBook( _                      9           "CS101 Introduction to Vis ual Basic Programming")  10        Dim gradeBook2 As New GradeBook("CS102 VB Data Structures") 11 12        ' display each GradeBook's course name (by invoking Get) 13        Console.WriteLine("gradeBook1's initial course name is: " & _ 14           gradeBook1.CourseName) 15        Console.WriteLine("gradeBook2's initial course name is: " & _ 16           gradeBook2.CourseName) 17        Console.WriteLine() ' display blank line 18 19        ' place in gradeBook1's course name a valid-length String 20        gradeBook1.CourseName = "CS101 VB Programming" 21 22        ' display each GradeBook's course name (by invoking Get) 23        Console.WriteLine( _ 24           "gradeBook1's course name is: " & gradeBook1.CourseName) 25        Console.WriteLine( _ 26           "gradeBook2's course name is: " & gradeBook2.CourseName) 27     End Sub ' Main 28  End Module ' GradeBookTest 

[View full width]

Name "CS101 Introduction to Visual Basic Programming" exceeds maximum length (25). Limiting course name to first 25 characters. gradeBook1's initial course name is: CS101 Introduction to Vis gradeBook2's initial course name is: CS102 VB Data Structures gradeBook1's course name is: CS101 VB Programming gradeBook2's course name is: CS102 VB Data Structures



GradeBook Class Definition

GradeBook's class definition in Fig. 4.15 contains all the same members as Fig. 4.12. Since the name and type of the property remain unchanged, clients of this class need not be changed when the definition of property CourseName is modified. This enables clients to take advantage of the improved GradeBook class without having to modify their own code.

Validating the Course Name with GradeBook Property CourseName

The enhancement to class GradeBook is in the definition of CourseName's Set accessor (Fig. 4.15, lines 1833). The If...Then statement in lines 1921 determines whether parameter value contains a valid course name (i.e., a String of 25 or fewer characters). If the course name is valid, line 20 stores it in instance variable courseNameValue. Note the expression value.Length in line 19. Length is a property of class String that returns the number of characters in the String. Parameter value is a String object, so the expression value.Length returns the number of characters in value. If value.Length is less than or equal to 25, value is valid and line 20 executes.

The If...Then statement in lines 2332 handles the case in which CourseName receives an invalid course name (i.e., a name longer than 25 characters). Even if the String in parameter value is too long, we still want to leave the GradeBook object in a consistent statethat is, a state in which the object's instance variable courseNameValue contains a String of 25 or fewer characters. We choose to truncate (i.e., shorten) the specified course name and assign the first 25 characters of value to the courseNameValue instance variable (unfortunately, this could truncate the course name awkwardly). Class String provides method Substring that returns a new String object created by copying part of an existing String object. The call in line 26 (i.e., value.Substring(0, 25)) passes two integers (0 and 25) to value's method Substring. These arguments indicate the portion of the string value that Substring should return. The first argument specifies the starting position in the original String from which characters are to be copiedthe first character in every string is considered to be at position 0. The second argument specifies the number of characters to copy. Therefore, the call in line 26 returns a 25-character substring of value starting at position 0 (i.e., the first 25 characters in value). For example, if value holds "CS101 Introduction to Visual Basic Programming", Substring returns "CS101 Introduction to Vis". After the call to Substring, line 26 assigns the substring returned by Substring to courseNameValue. In this way, property CourseName ensures that courseNameValue is always assigned a string containing 25 or fewer characters. If the property has to truncate the course name to make it valid, lines 2831 display a warning message. Note that line 29 displays a string of text that includes double quotes ("). Double quotes are normally used to delimit string literals, so to display double quotes in a string, you use two double quotes in a row.

Testing Class GradeBook

Figure 4.16 demonstrates the modified version of class GradeBook featuring validation. Lines 89 create a GradeBook object named gradeBook1. Note that the GradeBook constructor (lines 79 of Fig. 4.15) references property CourseName to initialize courseNameValue. In previous versions of the class, the benefit of referencing the property CourseName in the constructor was not evident. Now, however, the constructor takes advantage of the validation provided by the Set accessor of the CourseName property. The constructor simply assigns a value to CourseName rather than duplicate the Set accessor's validation code. When line 9 of Fig. 4.16 passes an initial course name of "CS101 Introduction to Visual Basic Programming" to the GradeBook constructor, the constructor passes this value to the Set accessor of CourseName, where the actual initialization occurs. This course name contains more than 25 characters, so the body of the second If...Then statement (lines 2332 of Fig. 4.15) executes, causing courseNameValue to be initialized to the truncated 25-character course name "CS101 Introduction to Vis" (the truncated part of the String is syntax shaded in bold black in line 9 of Fig. 4.16). The output in Fig. 4.16 contains the warning message output by lines 2831 of Fig. 4.15. Line 10 of Fig. 4.16 creates another GradeBook object called gradeBook2the valid course name passed to the constructor contains fewer than 25 characters (it contains 24 characters to be exact).

Lines 1316 of Fig. 4.16 display the truncated course name for gradeBook1 (we highlight this in bold black in the program output) and the course name for gradeBook2. Line 20 assigns a new value to gradeBook1's CourseName property, to change the course name in the GradeBook object to a shorter name that does not need to be truncated. Then lines 2326 output the course names for the GradeBook objects again.

A class's Set accessors cannot return values that indicate a failed attempt to assign invalid data to objects of the class. Such return values could be useful to a class's clients for handling errorsclients could then take appropriate actions. Chapter 12 presents exception handlinga mechanism that can be used (among other things) to notify a class's clients of attempts to set objects of that class to inconsistent states. To keep the program of Fig. 4.154.16 simple at this early point in the book, the CourseName property's Set accessor in Fig. 4.15 prints an appropriate message on the screen and sets courseNameValue to the first 25 characters of the specified course name.

Set and Get Accessors with Different Access Modifiers

By default, the Get and Set accessors of a property have the same access as the propertyin other words, for a Public property, the accessors also are Public. In Visual Basic, it is possible to declare the Get and Set accessors with different access modifiers. In this case, one of the accessors must have the same access as the property and the other must be more restrictive than the property. For example, in a Public property, the Get accessor might be Public and the Set accessor might be Private.

Error-Prevention Tip 4.2

The benefits of data integrity are not automatic simply because instance variables are made Privatethe programmer must provide appropriate validity checking and report the errors.


Error-Prevention Tip 4.3

Set accessors that set the values of Private data should verify that the intended new values are proper; if they are not, the Set accessors should place the Private instance variables into an appropriately consistent state.





Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net