Symbolic Constants

Consider this function:

Public Shared Function RemainingCarbonMass( _
   ByVal InitialMass As Double, _
   ByVal Years As Long _
) As Double
   Return InitialMass * ((0.5 ^ (Years / 5730)))
End Function

What’s wrong with this code? One problem is readability. What does it mean to divide Years by 5730? In this code, 5730 is referred to as a magic number -- one whose meaning is not readily evident from examining the code. The following changes correct this problem:

Public Const CarbonHalfLifeInYears As Double = 5730

Public Shared Function RemainingCarbonMass( _
   ByVal InitialMass As Double, _
   ByVal Years As Long _
) As Double
   Return InitialMass * ((0.5 ^ (Years / CarbonHalfLifeInYears)))
End Function

There is now no ambiguity about the meaning of the divisor.

Another problem with the first code fragment is that a program filled with such code is hard to maintain. What if the programmer later discovers that the half-life of carbon is closer to 5730.1 years, and she wants to make the program more accurate? If this number is used in many places throughout the program, it must be changed in every case. The risk is high of missing a case or of changing a number that shouldn’t be changed. With the second code fragment, the number needs to be changed in only one place.

See also the discussion of read-only fields later in this chapter, under Section 2.14.

Get Programming Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.