Non-ugly ways to implement a 'static' class or namespace?

Ali Çehreli acehreli at yahoo.com
Mon Jan 23 01:28:30 UTC 2023


On 1/22/23 16:21, thebluepandabear wrote:

 > Again, stuffing it into a module is not the same thing as a namespace.

That is correct but it is also one answer of D's to namespaces. There 
are others. For example, structs and classes provide namespacing as well.

 > The user can just bypass this by writing `drawLine`, there's nothing in
 > the language currently that would 'force' the user to write in a
 > namespace-like/static-class-like fashion, and that's the biggest problem.

I agree with Adam here. The language should provide solutions and the 
programmer should pick appropriate ones.

Later you added that you were talking about library design. There is no 
problem in the library providing an awesome and very usable API but the 
programmers still picking some other method that works better for them.[1]

I would like to add to your C++ examples:

   Keyboard::Key.A    // Fine
   Key.A              // Fine
   foo                // Fine

That last line can exactly be the same as the previous two in C++.

OOP is always a solution where it makes sense. I've been very happy with 
writing free-standing functions and dumb data types that the functions 
operate on... until... some invariant matters. Then I make the function 
a member, etc.

Perhaps because I don't buy into the "everything is a class" anymore, I 
am very happy with D's approach. Mostly structs and functions for me. 
But I use classes as well when they make sense.

Having said all that, I realize that your asking specifically for static 
classes made me think of a solution around classes. However, doesn't D 
has the equivalent in structs? Isn't the following what you are looking for?

struct Algo {
     static void drawLine(Canvas c, Pos from, Pos to) { ...... };
}

Now the user is forced to use it like this:

   Algo.drawLine(new Canvas(), new Pos(5, 3), new Pos(7, 9));

or this:

   Algo().drawLine(/* ... */);

but that can be @disabled.

Ali

[1] It is interesting that limiting the programmer in some way seems to 
help with language marketing. And D is deficient in that marketing move 
because it does the opposite: Gives the programmer choices. I tried to 
show this point on this slide: https://youtu.be/0JL9uT_XGZE?t=701 The 
point "not taking anything away from the programmer" can be seen as a 
marketing issue.



More information about the Digitalmars-d-learn mailing list