Code a Class*

Write code class code to define an object

You will write the code for a Person class that can be used to create (instantiate) multiple Person objects.

Steps to follow:

  1. Launch Visual Studio and start a new project of type Class Library.  You project should have the name Personnel.
  2. Write a new Person class with three properties, FirstName, LastName and DateOfBirth as show here:

person_class

NOTE:
Each property has a ‘container variable’ (e.g. stFirstName) which is where the property value will actually be stored when the property is assigned a value.  These container variables are declared with the keyword Dim, so they are only visible to the programs within the class; they are not part of the class’s public interface.  Access to these container variables is provided by the property procedures, which are sometimes referred to as accessor methods.
Save your project then build your solution.

  1. Start another instance of Visual Studio so it is running twice (hold down the shift key when you click the shortcut).
  2. In your second instance of Visual Studio, start a new project of type Windows Forms Application.  Your project should have the name FrontEnd.  (This will be contain the programs that a user can interact with.)
  3. Create a project reference to Personnel.dll which you built earlier (it is located in the Personnel/bin/Debug folder).
  4. Create two instances of your Person class, set their properties and output the values of their properties as shown here:

front_end

  1. Test your front end code.

NOTE:
You could implement a read only property by simply omitting the Set section of the property procedure.  Similarly, you can implement a write only property by omitting the Get section of the property procedure.

Validate a property value

You will now modify the date of birth property to validate that the Person is at least 18.

Steps to follow:

  1. Modify the DateOfBirth property as follows:

dob_validation

NOTE:
The DateOfBirth property, which is within the Person class, will call the Get sections of the FirstName and LastName properties, which are also within the Person class, in order to build the message that is displayed if the date of birth is invalid.  The keyword ‘Me’ is being used to denote that these properties are inside the same class.  This could have been done another way; the DateOfBirth method could have simply accessed the container variables for the FirstName and LastName properties like this:

method_accesses_container_variables

The preferred method is to call the properties as show here, in case these properties also contain additional processing validation which must be done.

  1. Rebuild your Personnel solution.
  2. Change the code in your front end to make one of the people too young and test your modifications.

Implementing a method

You will now add code for a method (also known as a ‘behaviour’) to your Person class, which will save the state of a Person object to a text file.  This method will be implemented as a sub procedure with the name SaveToFile, and will include a parameter for the full path and file name that can be passed to the method when it is called.

Steps to follow:

  1. Write a new public sub procedure in your Person class as follows:

         savetofile_method

  1. Rebuild your Personnel solution.
  2. Modify your front end so that it calls your new method for each Person object, after the property values have all been set correctly, as follows:

NOTE:
You may need to adjust the path.  You can specify the Documents folder of the current user like this:
p1.SaveToFile(My.Computer.FileSystem.SpecialDirectories.MyDocuments & “\newfile.txt”)

call_savetofile

  1. Test your new font end.  Examine the location you specified when you called your method.  There should be a new text file in there.

NOTE:
If you were building a real application, you would probably persist the state of an object in a database rather than a text file.  This could be achieved using ActiveX Data Objects (ADO).

Implement a method as a function

Methods can be implemented either as public procedures or public functions.  The one you just implemented was a procedure.  You will now improve your SaveToFile method by implementing it as a function that returns either True or False depending on whether it succeeded or not.  It is possible that the file location specified when this method is called could trigger a run time error.  Your improved version of the function will trap any problems and let the font end know about without crashing your application.

Steps to follow:

  1. Rewrite your SaveToFile method as follows:

savetofile_function_trycatch

NOTE:
Your SaveToFile method makes use of a Try Catch construct, which is the way run time errors (exceptions) are normally handled in modern versions of Visual Basic.  You could have used On Error Goto instead, like this:

savetofile_function_onerror

  1. Rebuild your Personnel solution.
  2. Modify your front end calls to your modified method to test the return value from the method whenever it is called as follows (you may need to adjust the path).  Notice that here you are trying to save p2 to a location on drive x, which triggers a run time error in the Person class that is handled in the Person class:

call_savetofile_function

Method overloading

You can create several versions of the same method, with each version expecting a different set of parameters.  This is known as ‘method overloading’ and each version of the method is known as an ‘overload’.  For example, when SaveToFile is called you may wish to pass the method an extra piece of information to be included with the saved person record, or you may not.

Steps to follow:

  1. Create an overload (a second version) of your SaveToFile method in your Person class as shown here.  The second version allows the caller to pass the name of the person who saved the record (the original version is also shown here):

method_overload

  1. Rebuild your Personnel solution.
  2. In your front end, retype your call the SaveToFile method and notice the option to select one or the other version of this method, depending on which parameters you want to pass.

call_overload_1

call_overload_2

  1. Complete your method call by including a value for the second parameter.

call_overload_2_2

You should now have two calls the SaveToFile method as shown here, one of which passes a single parameter, and the other of which passes two parameters.

both_overloads_called

  1. Test your front end and examine the text file to see if this worked.

Extension Task 1

Write the code for a Book class inside a class library with the name BookShop. Book should have the properties Title, Author, Genre and Price.  The Price property procedure should include validation in the Set section to ensure that the value is no less than £1 and no more than £100. Book should also have a method by the name of UpdatePrice, implemented as a function that returns a boolean True or False. The UpdatePrice method should expect two parameters, BookGenre and Discount.  When called for any book object, UpdatePrice should check to see if the BookGenre parameter it was passed matches the Genre property of the book, If it does match, it should reduce the value of the Price property by the specified amount then return True.   If it does not match, it should simply return False.   Test your Book from a client application.

Now define an overload of UpdatePrice, that expects three parameters, Genre, Author and Discount.  The Genre and Author must both match in order for the Price to be discounted.

Define a third overload of UpdatePrice with only one parameter for a Discount.  This should simply discount the price unconditionally.

Test your overloads from your a client application.

Extension Task 2

You will write a method inside your Person class to save the property values of a Person object into a Microsoft Access database.

Crate a new database in Access.  Give it a meaningful name.  It should have a table called tblPeople and the columns shown below. Note that the ID column is the primary key and that it is an AutoNumber data type.

Type the following Imports command above your Person class definition.  This will allow you to use the ActiveX Data Objects:

 

Write the following method overload in your Person class.  You may want to adjust the database path and file name.

Test your new method overload.  It should write a new record to your database table.