Disclaimer: I think the rules are almost the same in most OO languages, but since I’m most familiar with C# I’ll be relating to this specific language.
I think that the use of attributes and reflection could be largely reduced if static members would apply the same principles as OO instances.
Static properties and methods can be “overridden” by decedents by using the new keyword, but they cannot be forced to implement one via an interface, neither can the ‘base’ keyword be used (only explicitly naming the base type is supported). To make things worse, the members cannot be referenced via an instance, but have to always be specifically qualified with the exact type.
Constructors also have limited “inheritance” support, one can choose which base constructor is called, but you cannot force an object to support a constructor that takes certain parameters by defining it in an interface.
The best hint I could find to answer this question so far is this one on stack overflow (answering a different question).
In his answer Jörg points out three principals that apply to Object Orientation:
- messaging,
- local retention and protection and hiding of state-process, and
- extreme late-binding of all things.
Now I fully understand that if you want to pass on a state-full class from one method to another as an object, these principles make sense. However in my opinion the principle of inheritance, overriding base methods with alternative or additional functionality, could also be beneficial to stateless business logic.
One example where forcing an object to implement a certain constructor would be helpful is with de-serialization. For example where the constructor should accept an XML node. In C# it is dynamically implementable using reflection, but having compile-time errors and avoiding the reflection boilerplate would add lots of value!
Static method/member interfaces would be helpful in situations where some aspects of a value are type specific, without any relation to the instance. For example a class could have a DisplayName, Unit, Weight, Factor or other aspects that are the same across all instances of the specific type, regardless of the instance value. Attributes (or Annotation) can be used to exploit these without the need to create an instance, however, there again it’s extra boilerplate code and no way to enforce their implementation with compile-time errors.
I admit there are many simple ways to work around these points, I’m not looking for workarounds. Returning a static value in an instance-property is quite common, and it is not that much overhead to create an instance of an object just to read out the type-specific aspects, but I’d like to know the rationale background on why static things have been systematically excluded. I have heard about “the virtual stack” before, but don’t really know how it works technically (and cannot find any simple explanation on the net).
Are the reasons of technical or philosophical nature?
Edit: elaborating on static interfaces:
An example of how I think a static interface could provide a strongly typed, compiletime checked, alternative to reflection:
public staticInterface MyStaticInterface
{
constructor(XmlNode node);
string DisplayName { get; }
int Weight { get; }
}
The usage:
public void FillNodesToolBox()
{
MyStaticInterface[] nodes =
assembly.GetTypes().Where(t => t.Implements<MyStaticInterface>());
for (int i = nodes.Length - 1; i >= 0 ; i--)
{
Console.WriteLine(string.Concat(
nodes[i].DisplayName, " (", nodes[i].Weight.ToString(), ")"));
}
}
Looking back, this actually looks like making my Type object inherit from System.Type, adding some properties to it, which is different than a static member…
string.Empty != typeof(string).Emty
(the latter will not compile).
Maybe I’m starting to find the answer, but it feels like I’m walking in a paradoxical circle, it doesn’t quite ‘snap’ yet….
2
It simply cannot work.
Lets say you have class A that defines a “virtual” static method. Then you have classes B and C that derive from A and both override this static method. Then you call A.StaticMethod(). Which of the B or C should be called?
The reason why virtual methods are tied to instance is because the type of the instance specifies which implementation of the virtual method is called. If you don’t have this information, then you can’t call the proper method.
Also, if you try to argue that you have to call the static method on a type it is implemented in (eg. B.StaticMethod() or C.StaticMethod()), then that is not virtual method call and can already be implemented in C# without problems.
Now I fully understand that if you want to pass on a state-full class from one method to another as an object, these principles make sense. However in my opinion the principle of inheritance, overriding base methods with alternative or additional functionality, could also be beneficial to stateless business logic.
The business logic might seem stateless from abstraction’s viewpoint. So you design your interfaces or abstract classes around that. But then, you realize you want to parametrize specific behavior at runtime. With instance virtual methods this is easy. Just create new subtype that contains state specifies this parametrization. Nothing stops you from having stateless instances with just methods, but having ability to add state without changing the abstraction is huge advantage of OOP. By having the methods static, you are removing this advantage.
If you really think that “stateless” programming is better for your project, it might be good idea to look at functional programming, which is all about composing methods with minimal state keeping.
4
The reasons why an interface can’t dictate a constructor signature or the presence of static methods are primarily technical.
When calling method I::foo
of interface I
, the runtime environment needs a bit of metadata to know if it is actually X::foo
or Y::foo
that should be invoked. This metadata is specific for the object on which the method is invoked and thus attached to that object.
The problem with constructors and static methods is that they are invoked when there is no object available (yet). This means that there is no metadata available for the runtime environment to determine from which class to invoke the constructor or static method.
1
The conceptual reason interfaces can’t declare “abstract static members” is that the purpose of an interface is to specify what can be done with an object, not with a type. For example, the .NET interface IList<T>
is a type representing objects which behave as lists.
Now, it does make sense to specify a list of operations which can be performed on a type rather than an object. But such a thing is called a typeclass, not an interface.
Typeclasses
If C# supported typeclasses, then a typeclass declaration might look something like this:
typeclass CMonoidalList<T> of TList : IList<T>
{
TList(IEnumerable<T> contents); // a constructor
TList Append(TList suffix); // an instance method
}
A class implementing this typeclass could look like this:
class MyIntList : CMonoidalList<int>
{
public MyIntList(IEnumerable<int> contents) { ... }
public MyIntList Append(MyIntList suffix) { ... }
...
}
And a method which uses this typeclass would then look like this:
public static TList AppendString<TList>(TList list, string suffix)
where TList : CMonoidalList<char>
{
TList suffixList = new TList(suffix);
return list.Append(suffixList);
}
The problem with typeclasses
The downside of typeclasses, as compared to interfaces, is that typeclasses don’t make sense as types the way that interfaces do. It does not make sense to write code which treats CMonoidalList
as a type:
public static CMonoidalList<T> AppendBackwards<T>(
CMonoidalList<T> suffix, CMonoidalList<T> prefix)
{
return prefix.Append(suffix);
}
This code doesn’t make sense because Append
requires both prefix
and suffix
to be the same type implementing CMonoidalList<T>
, but the argument list of AppendBackwards
fails to express this.
This means that typeclasses are less convenient to use than interfaces, because you need to use where
everywhere. And besides, interfaces are an important concept in object-oriented programming, whereas typeclasses are not.
Interfaces can be better than typeclasses
Every typeclass you can think of does have a corresponding interface. The interface corresponding to your MyStaticInterface
would be:
public interface MyClassyInterface<T>
{
T New(XmlNode node);
string DisplayName { get; }
int Weight { get; }
}
This interface actually has an advantage over your typeclass: you can have multiple “implementations” of it for one single “implementing type” T
. Sometimes you might want to have lots of different DisplayNames
and Weights
without having to write a separate class for each one. When you do, having an interface instead of a typeclass will come in handy.
One downside to this is that now you have to actually pass around implementations of the interface, instead of just obtaining them automatically from the implementing type. Another downside is the fact that you can have multiple “implementations” for one single “implementing type”—maybe you want to restrict things to one implementation per type!
Other languages
Most languages don’t have typeclasses, presumably because they’re considered to be costly to implement (since, in general, most features are costly to implement) and wouldn’t provide all that much benefit.
Haskell has full-fledged typeclasses, along with all of their advantages and disadvantages. Haskell programmers use typeclasses a lot and generally don’t consider the disadvantages to be a very big deal.
Scala does not have typeclasses, but it has features to let you “fake it”. If you want to write a “typeclass” in Scala, you convert it into an interface (as I described above) and write that. When you want to have an “implementation of the typeclass”, you write an implementation of the interface and then declare that implementation as “implicit”. Then you won’t have to explicitly pass around implementations of the interface; the Scala compiler will try to make that happen completely automatically. It usually works.
Constructors also have limited “inheritance” support, one can choose which base constructor is called, but you cannot force an object to support a constructor that takes certain parameters by defining it in an interface.
An interface by definition has no knowledge of its underlying type. Technically there doesn’t even need to be an underlying type; an interface is simply a collection of functions. Although mainstream OOP languages have a built-in mechanism for interfaces and expect you to “attach” them to classes, you could just as well take a bunch of delegates/lambdas/functions with known signatures into some container type and that’d be an interface too.
One example where forcing an object to implement a certain constructor would be helpful is with de-serialization. For example where the constructor should accept an XML node.
In my opinion this is a bad idea. What happens when you want to serialize/deserialize the class in a different way? Or multiple ways at once? A class should have only one reason to change, and knowing how to serialize itself gives it a second reason. Granted, serialization is an interesting case because it requires breaking encapsulation, but I still feel it’s best handled externally.
Static method/member interfaces would be helpful in situations where some aspects of a value are type specific, without any relation to the instance. For example a class could have a DisplayName, Unit, Weight, Factor or other aspects that are the same across all instances of the specific type, regardless of the instance value.
A static field points to precisely one thing by definition; that’s why it’s not tied to any one instance of a class. Something can’t be static and overridable at the same time. Think about what overriding something means; you’d have something that knows how to locate the field you’re trying to access. That would make whatever you’re trying to get an instance field. It might not be an instance field of the instances of the class, but you’d be turning the class itself into an object.
As a final note, inheritance is already a problematic mechanism. It’s not inherently composable since you can only inherit from one thing at a time (otherwise you open up a different can of worms) and if you don’t put restrictions on what can be overridden, changes to the base class that would be safe when considered in isolation can break subclasses. Being able to override static fields would be of very dubious value.
16