4.8. Validating Data with Set Accessors in PropertiesIn 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.
Figure 4.16. Creating and manipulating a GradeBook object in which the course name is limited to 25 characters in length.
GradeBook Class DefinitionGradeBook'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 CourseNameThe 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 GradeBookFigure 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 ModifiersBy 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
Error-Prevention Tip 4.3
|