www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Static attributes & immutability, static attributes seen from instances

Nick Sabalausky Wrote:

 "Nick Sabalausky" <a a.a> wrote in message 
 news:hmsqdk$9ud$1 digitalmars.com...
 "bearophile" <bearophileHUGS lycos.com> wrote in message 
 news:hmrtbk$1aoi$1 digitalmars.com...
 A bit later in the discussion div0 and Pelle M. have said/suggested that 
 accessing static vars through an instance can be a bad thing, and it's 
 better to allow the programmer to access them only through the 
 class/struct name.


I've always felt that the ability to access static members through an instance was just a bad idea in general, and this seems to add another reason not to allow it.

The one possible exception I can think of (and I'm not even sure if it's applicable to D or not) is if you're passed an instance of something and want to call a static member of it polymorphically. Without polymorphism you can just do "typeof(instance).staticFunc()", but I'm not sure offhand whether or not there's a way to do that polymorphically (or if static members can even be polymorphic). However, I think that if people are calling static members through instances instead of types just to make the call polymorphic, then I'd consider that less of a reason to allow "instance.staticMember" and more of a reason to have some sort of polymorphic runtime equivilent to typeof() (Do we currently have such a thing that can suffice?).

In dynamic languages like Ruby, instances carry a pointer to their class instance which contains the "static" variables. say we have: class Foo { static int bar = 42; //... } foo = new Foo(); foo.bar is resolved at runtime as e.g. foo.Class.bar where Class is the singelton instance that represents the Foo class itself. if foo is const then D style transitivity would mean that bar must be const as well. regarding immutability, this is imposaible since the Foo singleton is shared between all (mutable and immutable) instances. In this case foo mustn't contain a Class member at all and have no access to it's data in order to keep the transitivity. D has a different implementation but I think the above semantics is what people expect and the implementation differences shouldn't affect the semantics, they should be encapsulated. IMO, the entire const design is backwards and ties toghether two completely separate concerns (immutability for conccurency and const for interface definitions) but there's zero change any of it will ever be changed.
Mar 08 2010