Re: Namespaces

new topic     » goto parent     » topic index » view thread      » older message » newer message

Ted Fines wrote:

> Could you please explain namespaces?

OK, the summary first:

   - namespaces exist to prevent name collisions

   - they allow you to use multiple libraries more easily

   - the allow developers to break large libraries into
     smaller files without polluting the global namespace


A name collision occurs when you include a file, and it tries to define a
variable or function with a name that's already in use. This is fairly
common, and programmers tend to use the same sort of naming convention. This
means the user of the library has to go into one of the files and change
names, which is a real pain.

For example, let's imagine that wanted to use a cool library of Jiri's, and
one of my own:

   include jiri_lib.e
   include my_lib.e

Both of us decided to include a global routine called 'abs' because Euphoria
hasn't got one. So in order to use both libraries, I'm going to have to
change the name of the routine in one of the two.

If there were namepaces, instead of the routines going into the 'global'
area, I could tell Euphoria to place them in a different space:

   include jiri_lib.e into jiri
   include my_lib.e into my

To refer to the routines in Jiri's library, I can write:

   jiri.abs()

and those in mine:

   my.abs()

That way, these routines can have the same name, yet still co-exist
peacefully together. So, from a user's point of view, namespaces mean you
can use libraries without having to go in and rename a bunch of routines if
there are collisions.

>From a coder's perspective, namespaces allow you to break up large files
into smaller chunks, and not 'pollute' the global namespace. Here's a simple
example of that:

   integer accumulator
   accumulator = 0

   global procedure add( integer i )
      accumulator += i
   end procedure

   global function clear()
      accumulator = 0
   end function

   global function sum()
      return accumulator
   end function

Here's the library in action:

   clear()
   add(12)
   add(334)
   add(-19)
   ? sum()

Pretty exciting, huh? smile

The routines that are declared as global are the interface that the library
creates. All the internal details are hidden from the user. For example, you
can use the library and never be aware that there's a variable called
'accumulator'.

This is fine and good, until libraries become large - for example, like
Win32Lib. Imagine you broke the example library in half. For it to work, you
would have to declare things that rightfully had been local as global:

   global integer accumulator

And we're back to the problem of name collisions again. With namespaces, you
should be able to avoid this problem.

I hope this helps!

-- David Cuny

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu