What's New
Q & A
Tip Jar
What Are Classes For and Why Are They Useful?
Rod Stephens (RodStephens@vb-helper.com)
Suppose you have a program that keeps a list of strings sorted. Routines to manage the list are in a BAS file. You call the AddString routine to add a string, and it automatically rearranges the strings so they are sorted. You can then look at the list array to see the strings in their sorted order.

Now suppose you have a program that needs two such lists. You are stuck. You need to create a whole new BAS file with almost exact duplicates of the other file's routines to manage the new list.

Imagine another program that does not know ahead of time how many lists it might need. Now you are really stuck. Unless you know how many lists to make, you cannot give them separate arrays to manage and separate BAS files to work with.

On the other hand, suppose you implement the list as a class. It contains its own list array and routines that work with that array. Now you can create any number of sort list objects using this class. The program does not need to know ahead of time how many it needs; it just uses New to build new lists whenever necessary. The program also only needs one copy of the code in the clas module instead of lots of almost identical code to manage different arrays.

Notice that this sorted list class has data (the values) and routines that manipulate the data (add items and keep it sorted, etc.). It's basically a data structure like a user-defined type (UDT), except it has routines attached to the data.

That is one sign of a good class. If it had only data, you could implement it as a UDT. If it contained only routines, you could put the routines in a BAS file. The fact that the routines must be attached to particular pieces of data makes it a good candidate for a class.

What are some other examples?

  • Employee. A business application could have an Employee class. If the class does nothing more than hold data about employees, this is overkill. It could just as easily be a UDT. On the other hand, it could supply routines that manipulate the Employee data (calculate vacation, taxes, investment contributions, etc.). In that case it would make a reasonable class.
  • Matrix. This stores the numbers in a matrix. It can include routines to multiply matrices, multiply a matrix by a vector, etc. You could make a matrix be a UDT and make the routine be in a BAS module, but making this a class keeps the data and code in one module so it is easy to find.

Subscribe to the VB Helper newsletter
Copyright © 1997-2001 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
www.vb-helper.com/essay4.htm Updated