Sunday, October 31, 2010

Custom Classes

Alright, today we are going to talk about custom classes.  This is, in my opinion, a really cool aspect of Object Orientated Programming.  This allows you to create custom data types that can be used throughout your project.  Not only does this save tons of code, but it makes keeping your program organized easier and makes everything look neater.

The difficulty is EASY!!!

Ok, let's say you are writing a program that will track gas mileage for cars.  Now lets pretend that you are writing the piece of code that will deal with adding a new trip.  Let's say you have a form that has places to put in the different pieces of data.  Let's also assume that you have a database class that is used to read and write from the database. You could write:

Dim tripMileage as Int16
Dim tripDate as Date
Dim gasUsed as Double




DataBase.AddTrip(tripMileage, tripDate, gasUsed)


And that would work fine.  But when you got to a point where you wanted to list all of the trips a user had put in, what are you going to do?


You could:
Dim tripMileage() as Int16
Dim tripDate() as Date
Dim gasUsed() as Double


This would be creating arrays of each type to use to store the data for each trip.  The biggest problem with that is you must know beforehand how many trips you are dealing with.  Also I personally never liked using arrays like this.  What I would recommended doing is create a class called Trip.vb and using it to store trip information as its own data type.  Ex:


Public Class Trip
  Public tripMileage as Int16
  Public tripDate as Date
  Public gasUsed as Double


  Public sub new()
    tripMileage = 0
    tripDate = new Date()
    gasUsed = 0.0
  End Sub
End Class


Then you could have the sub that gives you the list of every trip just give you an ArrayList of type Trip.  You would use these trips as data types in your programming like this:


Dim t as new Trip()
t = DataBase.getNewestTrip()
labelTripMileage.Text = t.tripMileage
labelTripDate.Text = t.tripDate.ToShortDateString()
labelGasUsed.Text = t.gasUsed
labelGasMileage.Text = Math.Round(t.gasUsed / t.tripMileage, 2)


As you can see the variable t is of type Trip, this can make things a lot easier when programming to have a data type that is exactly what you are dealing with in your program.  


I hope you had fun and learned something.  If you have any good ideas for topics, feel free to email them to me.

No comments: