Skip to Content
Programming Visual Basic .NET
book

Programming Visual Basic .NET

by Dave Grundgeiger
December 2001
Beginner
464 pages
13h 51m
English
O'Reilly Media, Inc.
Content preview from Programming Visual Basic .NET

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Visual Basic .NET, Second Edition

Programming Visual Basic .NET, Second Edition

Jesse Liberty

Publisher Resources

ISBN: 0596000936Supplemental ContentCatalog PageErrata