Free functions versus member functions

Chad J gamerChad at _spamIsBad_gmail.com
Thu Oct 11 04:17:41 PDT 2007


Regan Heath wrote:
> 
> What about D's modules or packages, aren't they the equivalent of a 
> namespace?  If not, what do they lack?
> 
> Regan

I'm not sure about namespaces, but one thing that putting stuff in 
structs/classes does is it forces users to state where the 
functions/data they are using comes from.  It's forced FQN (Fully 
Qualified Name) syntax in a sense.  It is nicer than just using 
module-based FQN because Stdout.formatln() is shorter than 
tango.io.Stdout.formatln() and still gets the point across.  It would be 
nice to be able to write stdio.writefln(), which wouldn't lose much 
since it is very unlikely that there will be a series of imports like so:
std.stdio;
somelib.stdio;
somelib.subpackage.stdio;
In above such cases, well, too bad.  Someone trying to figure out where 
stdio.writefln came from will just have to look it up.


I may have just conflated two things unfortunately: compulsory FQN vs. 
voluntary FQN is one, and the other is the notion of a partially 
qualified name (PQN?).  Currently D modules are voluntary FQN, while 
structs/classes act as compulsory PQN.



Another thing that makes me tend to throw things into structs and 
classes is that private-is-visible.

Consider this:

//main.d
import std.stdio;
import primary;
import secondary;

void main()
{
   writefln( generate() );
}

// primary.d
public char[] generate()
{
   return "Hello from primary!";
}

// secondary.d
private char[] generate()
{
   return "Hell from secondary!";
}

Compiling the above code results in the following error:
main.d(7): Error: primary.generate at primary.d(2) conflicts with 
secondary.generate at secondary.d(2)

When I declare something private, I generally don't want it to affect 
anything in other modules, at all.  Other modules do get affected in D, 
in the form of compiler errors, but a similar effect can be gained by 
just throwing things into structs or classes.

This has been discussed before.  I remember Walter liking it this way. 
It was to allow people to "poison" certain function overloads.  It's a 
small thing, but annoying.



More information about the Digitalmars-d mailing list