- A Simple Temperature Conversion Program
- Building a Temperature Class
- Putting the Decisions into the Temperature Class
- Using Classes for Format and Value Conversion
- A String Tokenizer Class
- Classes as Objects
- Class Initialization
- Classes and Properties
- Another Interface Example·The Voltmeter
- A vbFile Class
- Programming Style in Visual Basic
Another Interface Example—The Voltmeter
Suppose that you need to interface a digital voltmeter to your computer. We'll assume that the meter can connect to your serial port and that you send it a string command and get the measured voltage back as a string. We'll also assume that you can set various measurement ranges such as millivolts, volts, and tens of volts. The methods for accessing this voltmeter might look like this.
'The Voltmeter class Public Sub setRange(ByVal maxVal As Single) 'set maximum voltage to measure End Sub '------ Public Function getVoltage() As Single 'get the voltage and convert it to a Single End Function
The nice visual data-gathering program you then write for this voltmeter works fine, until you suddenly need to make another simultaneous set of measurements. You discover that the model of voltmeter that you wrote the program for is no longer available and that the new model has different commands. It might even have a different interface (IEEE-488 or USB, for instance).
This is an ideal time to think about program interfaces. The simple two-method interface we specified previously should work for any voltmeter, and the rest of the program should run without change. All you need to do is write a class for the new voltmeter that implements the same interface. Then your data-gathering program only needs to be told which meter to use and it will run completely unchanged, as we show here.
Private Sub OK_Click() If opPe.Value Then Set vm = New PE2345 Else Set vm = New HP1234 End If vm.getVoltage End Sub
Further, should your data needs expand so that there are still more meters, you can quickly write more classes that implement this same Voltmeter interface. This is the advantage of OO programming in a nutshell: Only the individual classes have detailed knowledge of how they work. The only external knowledge is contained in the interfaces.