Could a singleton type replace static methods and classes?
Posted
by
MKO
on Programmers
See other posts from Programmers
or by MKO
Published on 2011-03-10T13:06:57Z
Indexed on
2011/03/10
16:19 UTC
Read the original article
Hit count: 195
In C# Static methods has long served a purpose allowing us to call them without instantiating classes. Only in later year have we became more aware of the problems of using static methods and classes.
- They can’t use interfaces
- They can’t use inheritance
- They are hard to test because you can’t make mocks and stubs
Is there a better way ? Obviously we need to be able to access library methods without instantiated classes all the time otherwise our code would become pretty cluttered
One possibly solution is to use a new keyword for an old concept: the singleton. Singleton’s are global instances of a class, since they are instances we can use them as we would normal classes. In order to make their use nice and practical we'd need some syntactic sugar however
Say that the Math class would be of type singleton instead of an actual class. The actual class containing all the default methods for the Math singleton is DefaultMath, which implements the interface IMath. The singleton would be declared as
singleton Math : IMath
{
public Math
{
this = new DefaultMath();
}
}
If we wanted to substitute our own class for all math operations we could make a new class
MyMath that inherits DefaultMath, or we could just inherit from the interface IMath and create a whole new Class. To make our class the active Math class, you'd do a simple assignment
Math = new MyMath();
and voilá! the next time we call Math.Floor it will call your method. Note that for a normal singleton we'd have to write something like Math.Instance.Floor but the compiler eliminates the need for the Instance property
Another idea would be to be able to define a singletons as Lazy so they get instantiated only when they're first called, like
lazy singleton Math : IMath
What do you think, would it have been a better solution that static methods and classes? Is there any problems with this approach?
© Programmers or respective owner