- 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
- Summary
Putting the Decisions into the Temperature Class
Now we are still making decisions within the user interface about which methods of the temperature class. It would be even better if all that complexity could disappear into the clsTemp class. It would be nice if we just could write our Conversion button click method as
Private Sub btConvert_Click() Dim clTemp As New clsTemp 'put the entered value and conversion request 'into the class clTemp.setEnterTemp txTemperature.Text, opFahr.Value 'and get out the requested conversion lbNewtemp.Caption = clTemp.getTempString End Sub
This removes the decision-making process to the temperature class and reduces the calling interface program to just two lines of code.
The class that handles all this becomes somewhat more complex, however, but then it keeps track of what data as been passed in and what conversion must be done.
Private temperature As Single 'always in Celsius Private toFahr As Boolean 'conversion to F requested Public Sub setEnterTemp(ByVal tx As String, _ ByVal isCelsius As Boolean) 'convert to Celsius and save If Not isCelsius Then makeCel tx 'convert and save toFahr = False Else temperature = Val(tx) 'just save temperature toFahr = True End If End Sub '------ Private Sub makeCel(tx As String) temperature = 5 * (Val(tx) - 32) / 9 End Sub
Now, the isCelsius Boolean tells the class whether to convert and whether conversion is required on fetching the temperature value. The output routine is simply the following.
Public Function getTempString() As String getTempString = Str$(getTempVal) End Function '------ Public Function getTempVal() As Single Dim outTemp As Single If toFahr Then 'should we convert to F? outTemp = makeFahr 'yes Else outTemp = temperature 'no End If getTempVal = outTemp 'return temp value End Function '------ Private Function makeFahr() As Single Dim t As Single 'convert t to Fahrenheit t = 9 * (temperature / 5) + 32 makeFahr = t End Function
In this class we have both public and private methods. The public ones are callable from other modules, such as the user interface form module. The private ones, makeFahr and makeCel, are used internally and operate on the temperature variable.
Note that we now also have the opportunity to return the output temperature as either a string or a single floating point value and could thus vary the output format as needed.