Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Namespaces

A module keeps names apart between directories. Inside one file, a namespace does the same job: it gives a group of names a family name, so two parts of a program can each have an Area.

'' A namespace gives a group of names a family name, inside one file.
namespace Metric
    const CM_PER_M = 100

    function Area( byval w as float64, byval h as float64 ) as float64
        return w * h
    end function

    '' Namespaces nest.
    namespace Convert
        function ToInches( byval cm as float64 ) as float64
            return cm / 2.54
        end function
    end namespace
end namespace

namespace Imperial
    '' The same name in another namespace is a different procedure.
    function Area( byval w as float64, byval h as float64 ) as float64
        return w * h * 144      '' square feet to square inches
    end function
end namespace

'' A namespace can be reopened to add more names.
namespace Metric
    function Perimeter( byval w as float64, _
                        byval h as float64 ) as float64
        return 2 * ( w + h )
    end function
end namespace

print "metric area:  "; Metric.Area( 2, 3 )
print "imperial area:"; Imperial.Area( 2, 3 )
print "perimeter:    "; Metric.Perimeter( 2, 3 )
print "inches:       "; Metric.Convert.ToInches( 254 )

'' using makes the names bare until the end of the block.
sub Report( )
    using Metric
    print "in Report:    "; Area( 4, 5 ); CM_PER_M
end sub

Report( )

Output

metric area:   6
imperial area: 864
perimeter:     10
inches:        100
in Report:     20 100
  • Outside the namespace, a member is written qualified: Metric.Area, Imperial.Area. Inside it, the bare name is enough.
  • Namespaces nest, and the full path is written out: Metric.Convert.ToInches.
  • A namespace can be reopened. The second namespace Metric block adds Perimeter to the same namespace.
  • using Metric inside Report makes the members usable bare until the end of Report. Written at the top level, it lasts to the end of the file.

A name declared closer to where it is used always beats one that using brings in, so adding a using never changes the meaning of a name you already had.

Use a module for code that other files or programs share; a module is already a namespace, with visibility rules on top. Use namespace to group names within a file, or in a header that must stay a header.

Activities

  1. Add Imperial.Perimeter and call both Perimeters.
  2. Put using Metric and using Imperial in one sub and call Area bare. What does the compiler say?