[Issue 6579] Calling static method should *require* using type and not instance

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Aug 30 08:47:16 PDT 2011


http://d.puremagic.com/issues/show_bug.cgi?id=6579



--- Comment #1 from Steven Schveighoffer <schveiguy at yahoo.com> 2011-08-30 08:47:13 PDT ---
This is in response to: http://d.puremagic.com/issues/show_bug.cgi?id=3345#c3

It's only a poorly chosen name because of the way you can call static functions
on instances.

What would be a better name, resetStatic()?  I mean, why must I repeat that
it's static, I've already said it was static!

The problem is the coupling between static function names and instances is not
an obvious connection.  When naming a static function one seldom considers how
it will read if called on an instance, because one's expecting people to use
the class/struct name to call it.

Another example, let's say you have a File struct (not unheard of).  Then you
want a static method to open a file.  A logical thing to do would be:

struct File
{
   static File open(string name) {...}
}

expecting the usage:

auto f = File.open("blah.txt");

However, that makes this also valid:

File f;

f.open("blah.txt");

Which doesn't do even close to what you would expect it to, yet compiles
happily.

I can't even think of a way to name that function which makes it look like
"you're doing the wrong thing" on the instance, yet is good enough to be used
as a function name.

A solution can be to just put the function outside the struct, calling it
openFile.  But it almost feels like D is discouraging static methods, use
global functions instead.

I dispute that this is more annoying for generic code.  Calling a static method
from an instance is not a usual occurrence, and typically type names in generic
code are T or S.  How horrible is it to do T.foo() vs. t.foo()?

Note that even though this would be a breaking change, it would be a loud one,
not a silent one.  Any existing code relying on calling static methods from
instances would not compile.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list