Small Basic - Avoiding the Else

Avoiding the Else

Let’s say you want to create a program that monitors the state of a system by watching its temperature. If the temperature’s below 100°, the program tells your user that the system’s running normally. If the temperature’s 100° or more, then it displays a warning message. The code below shows you one way to write this program, along with the output from two sample runs.

 

' Helps monitor the temperature of a system

TextWindow.Write( "Enter the temperature of the system: " )

temp = TextWindow.ReadNumber()

 

If ( temp < 100 ) Then

   msg = "The system is running normally."

Else

    msg = "Warning! The system is overheating."

EndIf

 

TextWindow.WriteLine( msg )

 

Output:

Enter the temperature of the system: 90

The system is running normally.

 

Enter the temperature of the system: 110

Warning! The system is overheating.

 

Look how the program sets the msg variable to different strings, based on the current temperature (in Lines 7 and 9), and then it displays that message (Line 11). See this next example for a different way to write this program.

 

' Monitors the temperature of a system

 

TextWindow.Write( "Enter the temperature of the system: " )

temp = TextWindow.ReadNumber()

 

msg = "The system is running normally."

' Assume normal

 

If ( temp >= 100 ) Then          ' and if it isnt normal

msg = "Warning! The system is overheating."

                                 ' change your assumption

EndIf

 

TextWindow.WriteLine( msg )

 

The program above assumes that the system’s running normally and gives the msg variable the message, "The message is running normally." Your program then checks to see if the assumption’s true (temp >= 100). If the system’s running normally (the temperature’s below 100 degrees), then the program continues to display the message, "The message is running normally." If the temperature is 100 degrees or more, then your program updates the msg variable with the warning message ("Warning! The system is overheating") and continues to write the line at the end to warn your user. You were able to eliminate the Else block completely!

This style (of using an If statement to change a variable’s default value) is very common among programmers, so you should get used to it. You’ll see both this style and the If/Else style used in the community.

 

Why are we explaining these alternatives? So that you can understand the differences and will be able to know what the code is doing when you see other peoples' code!

  

Have a Small and Basic day!

   - Ninja Ed and Majed Marji