Do I still have to implement a singleton class by hand in .net, even when using .Net4.0? - .net-4.0

Once the singleton pattern is understood, writing subsequent singleton classes in C# is a brainless exercise. I would hope that the framework would help you by providing an interface or a base class to do that. Here is how I envision it:
public sealed class Schablone : ISingleton<Schablone>
{
// Stuff forced by the interface goes here
// Extra logic goes here
}
Does what I am looking for exist?
Is there some syntactic sugar for constructing a singleton class - whether with an interface, a class attribute, etc.?
Can one write a useful and bullet-proof ISingleton themselves? Care to try?
Thanks!

How often do you find yourself writing singleton classes?
I'd suggest that if it's a sufficiently frequent task for you that you feel you're losing productivity, you may well be overusing the pattern. I find that it's very rarely appropriate - but can easily lead to hard-to-test code.
Writing a singleton class in C# isn't just brainless - it's almost entirely painless. The boiler plate required is tiny, assuming you don't require absolute laziness to the point where the singleton shouldn't be instantiated just by calling other static methods.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
private Singleton() {}
// Omit if you don't care about type initializer laziness
static Singleton() {}
}
Obviously you'd need a class declaration anyway, so you've saved either three or four lines, depending on whether you need the static constructor. Personally I don't think that's so time consuming for the rare occasions on which a singleton is valid that it's worth being part of the framework.
Indeed, it's hard to see how it could be a framework feature rather than a language feature... at the very least the compiler would have to be aware of it, to understand that there will be some magic "Instance" property (or whatever) that it should make available to callers.
As Eric Lippert is fond of pointing out (entirely reasonably, I might add) language features have great costs associated with them in terms of design, implementation and testing. Furthermore, there's the burden of each developer learning about the new language feature. In short, they need to really earn their value - and for me, the singleton pattern isn't sufficiently useful and important that it makes the bar.

What is there to force? A singleton can be implemented with as little as a single property and a field. It doesn't seem like there is a very good value/cost ratio here for any framework developers to bother with.
Not to mention, the singleton pattern is often a poor one to use, and IMO it'd be bad to have the framework promoting them. To me, a singleton is almost always a code smell.

As others and me (in comments) have pointed out, the singleton pattern is rarely appropriate.
Still, since some believe that this could not work, here's the helper class to implement such a singleton (inspired by the linked article about how to implement singletons):
public static class Singleton<T> where T: class, new() {
public static T Instance {
get {
return Nested.instance;
}
}
private static class Nested {
public static readonly T instance = new T();
static Nested() {}
}
}
The class to be used as singleton needs to have a public default constructor.
You could then use it as follows:
Singleton<MyClass>.Instance.DoSomething();

No, there is nothing in the .Net framework like this. You have to write singletons yourself. It would be a bit hard to have a definative API for singletons as there are so many ways of implementing them, and depending on your goals depends on what approach you will take.
I would suggest you read this article on singletons. (Written by Jon - He's a wise guy, listen to him) for guidance and tips on the various techniques. It covers some stuff that most people might not have thought about.
[A lot of people consider the singleton pattern to be a dubious design pattern. I won't go into the reasons here, but if your interested google has loads of info. Just be careful you don't overuse it unnecessarily.]

I don't think that is possible.
How would an interface prohibit you from adding a public constructor to your class?
After all, writing a singleton is not that much work once you understood the basic pattern (and the caveats of making it thread-safe).

Cut. Paste. Next.

Use an Inversion of Control container to manage it for you.
With StructureMap, you can declare any type as a singleton:
ObjectFactory.Initilialize(x => x.ForSingletonOf<Schablone>());
To retrieve it:
ObjectFactory.GetInstance<Schablone>();

.Net 4.0 comes with MEF. And you can use MEF to instantiate a singleton. Thru the shared creation policy. I'll dig out a code sample....
EDIT ----
better still, here's some doco....
http://mef.codeplex.com/wikipage?title=Parts%20Lifetime&referringTitle=Guide

Related

How do you avoid subclass call-backs when using Composition?

So I tend to favour composition over inheritance and I would like non-inheritance answers for this question.
There appears to be circumstances when using composition when there is some code in the superclass that requires a call to code in the subclass. This makes for unscaleable inheritance hierarchies which defeats the purpose of using composition in the first place. Here's a demonstration of the problem in C# (although this is a general oop question):
public interface IChemistry
{
void SeparateAtom(Atom atom);
void BreakBond(Bond bond);
}
public class BaseChemistry : IChemistry
{
public void SeparateAtom(Atom atom)
{
//possible extra logic here
for(int i=0;i < atom.BondCount;i++)
{
//maybe extra logic here etc.
BreakBond(atom.Bonds[i]);
}
}
public void BreakBond(Bond bond)
{
//do some bond breaking logic here
}
}
public class RealisticChemistry : IChemistry
{
private BaseChemistry base;
public RealisticChemistry(BaseChemistry base)
{
this.base = base;
}
public void SeparateAtom(Atom atom)
{
//subclass specific logic here perhaps
base.SeparateAtom(atom);
}
public void BreakBond(Bond bond)
{
//more subclass specific logic
base.BreakBond(bond);
}
}
As you can see with this design there is a glaring problem. When the subclass' SeparateAtom() method is called it executes some of it's own logic and then delegates the rest to the base class which will then call the BreakBond() method on the base class, not on the subclass.
There are various solutions I can think of for this and almost all of them have pretty substantial setbacks:
Copy and paste. The worst option in this case would be to simply copy the loop (and additional logic) within the base class' SeparateAtom() method, to the subclass' one. I don't feel that it is necessary to explain why copy and paste is not the best practice. Another option could be to package some of the extra logic around the loop into extra methods so that it's just the loop that is copied. But the calls to the additional methods are still copied, and breaking things up into multiple methods could break encapsulation. For example what if some of that logic is dependent on the specific context of SeparateAtom()and could lead to faulty data if called out-of-context by someone who does not know the code very well?
Listen to or observe bond breaking events in base class. This solution seems problematic to me because the way in which base class functionality should be extended becomes unclear. For example, without prior knowledge if one were to try to extend the class they might intuitively implement the design above and interpret the listener as optional, when it is in fact required if one wants to extend bond breaking behaviour.
Make the base class require a delegate. For example, the base class could require a reference to a IBondBreakDelegate which is called inside of BondBreak(). This has a similar problem to the listener approach in that the mixture of composition and other approaches makes the intended usage of the base class unclear. Also, even though now there is a delegate which is actually required, thus making the intended usage a little more clear, the base class can now no longer function on its own. Also if one needs to extend the hierarchy with an additional subclass (for example public class MoreRealistiChemistry etc.), how would one go about extending the delegated behaviour through composition?
Delegate everything instead of composition. I would prefer not to go down this route because when classes need extra functionality the amount of delegates needed increases (or the amount of methods in the delegates does). Also what if some of the delegated behaviour is optional? Then either there needs to be separate optional delegates for each behaviour that the subclass implements, or you end up with lots of empty method bodies in the subclass.
In general when I commit to a type of design, I would like to do so wholeheartedly. Of course in the real-world there are a ton of caveats. But I feel like this one must be so common that someone might know a good work-around. Any ideas?
(I cannot add a comment because of insufficient reputation, but I want to point out two things.)
First, your code does not compile because the classes do not implement IChemistry.
Second, 'favour composition over inheritance' is only a guideline and is not meant to be applied mindlessly. If the model that is under consideration for the solution requires either inheritance or composition, you should choose composition.
For this particular question, inheritance (or rather, specialisation) is the more sensible approach.

Should Interface implementations be independent

I have come across some legacy code that has raised all my heckles as an Object Oriented Programmer.
Here's the pattern used often:
An interface has two implementations and one implementation calls a method of the other.
Now, I think it should be refactored so that the implementations do not know about each other. It is simple enough HOW to do it. What I cannot figure out clearly - & hoping good people of SO would help me with - is WHY.
I can see the theoratical reason - it is a terrible object-oriented design. But I am playing the devil's advocate here and asking - what is the practical disadvantage of two implementation having knowledge of each other. Why should time & money be spent to get rid of this (in my mind) anti-pattern?
Any info or links on this will be appreciated.
I can see the theoratical reason - it is a terrible object-oriented design.
Why? It sounds entirely reasonable to me.
For example, suppose I want to decorate every call - e.g. to add statistics for how often a call has been made, or add some authorization check etc. It makes sense to keep that decoration separate from the real implementation, and just delegate:
public class DecoratedFoo : IFoo
{
private readonly IFoo original;
public DecoratedFoo(IFoo original)
{
this.original = original;
}
public string Bar() // Defined in IFoo
{
// Update statistics here, or whatever
return original.Bar();
}
}
Why do you view that separation of concerns to be "terribly object-oriented design"? Even if the decorated class knows about a specific implementation of IFoo and calls members which aren't part of IFoo itself in order to make things more efficient, it doesn't seem particularly awful to me. It's just one class knowing about another, and they happen to implement the same interface. They're more tightly coupled than the example above which only knows about IFoo, but it's still not "terrible".
There is nothing wrong with an implementation1 of interface1 being aware of or interacting with implementation2 of interface1.
I think you have just spotted an intended or un intended implementation of proxy pattern
http://en.wikipedia.org/wiki/Proxy_pattern
Hope this helps :)
My thoughts on this are
Suppose in the due course of time if you are retiring one implementation and you have kept that separately then there is no change in the other and you dont need to test that. If there is no separation you need to spend time in separating and testing the other implementation.
Its always cleaner to have single responsibility.
That method of the "other implementation" that the first implementation calls is what I would call a library function. Put it in a separate module/file/project/whatever (depends on your language/dev env) and have both implementations include it and use it from there.
There is absolutely nothing wrong with two implementations of some interfacing containing common code, but of course that common code should probably be separated from each implementation so that you can load either into your program without having to load the other.

IOC containers and IDisposable

It was recommended to me that, when using an IOC container, I should change this:
class Foobar: IFoobar, IDisposable {};
Into this:
interface IFoobar: IDisposable{};
class Foobar : IFoobar{};
I'm wondering if this is ok, or if it solves one problem and creates another. It certainly solves the problem where I badly want to do this:
using( IFoobar = myContainer.Resolve<IFoobar>() )
{ ... }
And now I know that any substitute won't cause a run-time error.
On the other hand, now all my mock objects must handle IDisposable too. Am I right that most any mocking framework handles this easily? If yes, then perhaps this is a non-issue.
Or is it? Is there another hidden gotcha I should watch for? It certainly occurs to me that if I were using an IOC container not for unit tests / mocking, but for true service independence, then this might be a problem because perhaps only one of my swappable services actually deals with unmanaged resources (and now I'm having to implement empty "IDispose" operations in these other services).
Even this latter issue I suppose I could live with, for the sake of gaining the ability to employ the "using" statement as I demoed above. But am I following a popular convention, or am I missing an entirely different and better solution?
Deriving an interface from IDisposable is in my opinion a design smell that indicates a Leaky Abstraction. As Nicholas Blumhardt put it:
an interface [...] generally shouldn't be disposable. There's no way for the one defining an interface to foresee all possible implementations of it - you can always come up with a disposable implementation of practically any interface.
Consider why you want to add IDisposable to your interface. It's probably because you have a particular implementation in mind. Hence, the implementation leaks into the abstraction.
An DI Container worth its salt should know when it creates an instance of a disposable type. When you subsequently ask the container to release an object graph, it should automatically dispose the disposable components (if their time is up according to their lifestyles).
I know that at least Castle Windsor and Autofac does this.
So in your case, you should keep your type like this:
class Foobar: IFoobar, IDisposable {};
You may find Nicholas Blumhardt's post The Relationship Zoo interesting as well - particularly the discussion about Owned<T>.

Is it bad practice to have a class that requires a reference to the instantiating object?

I saw this in someone's code and thought wow, that's an elegant way to solve this particular problem, but it probably violates good OO principles in an epic way.
In the constructor for a set of classes that are all derived from a common base class, he requires a reference to the instancing class to be passed. For example,
Foo Foo_i = new(this);
Then later on Foo would call methods in the instancing class to get information about itself and the other objects contained by the instancing class.
On the one hand, this simplifies a TON of code that models a 5-layer tree structure in hardware (agents plugged into ports on multiple switches, etc). On the other hand, these objects are pretty tightly coupled to each other in a way that seems pretty wrong, but I don't know enough about OOA&D to put my finger on it.
So, is this okay? Or is this the OO equivalent to a goto statement?
You shoud try to avoid mutual references (especially when implemeting containment) but oftentimes they are impossible to avoid. I.e. parent child relationship - children often need to know the parent and notify it if some events happen. If you really need to do that - opt for interfaces (or abstract classes in case of C++).
So you instancing class should implement some interface, and the instanciated class should know it only as interface - this will sigificantly reduce coupling. In some respect this approach is similar to nested listener class as it exposes only part of the class, but it is easier to maintain. Here is little C# example:
interface IParent
{
//some methods here
}
class Child
{
// child will know parent (instancing class) as interface only
private readonly IParent parent_;
public Child(IParent parent)
{
parent_ = parent;
}
}
class Parent : IParent
{
// IParent implementation and other methods here
}
This sounds like it could be violating the Law of Demeter, depending on how much Foo needs to know to fish around in the instancing class. Objects should preferably be loosely coupled. You'd rather not have one class need to know a lot about the structure of another class. One example I've heard a few times is that you wouldn't hand your wallet over to a store clerk and let him fish around inside. Your wallet is your business, and you'll find what you need to give the clerk and hand it over yourself. You can reorganize your wallet and nobody will be the wiser. Looser coupling makes testing easier. Foo should ideally be testable without needing to maintain a complex context.
I try and avoid this if I can just from an information hiding point of view. The less information a class has or needs the easier it is to test and verify. That being said, it does lead to more elegant solutions in some cases so if not doing it is horribly convoluted involving an awful lot of parameter passing then by all means go for it.
Java for example uses this a lot with inner classes:
public class Outer {
private class Inner {
public Inner() {
// has access to the members of Outer for the instance that instantiated it
}
}
}
In Java, I remember avoiding this once by subclassing certain Listeners and Adapters in my controller and adding those listeners and adapters to my subclasses.
In other words my controller was
class p {
private member x
private methods
private class q {
// methods referencing p's private members and methods
}
x.setListener(new q());
}
I think this is more loosely coupled, but I would also like some confirmation.
This design pattern can make a lot of sense in some situations. For example, iterators are always associated with a specific collection, so it makes sense for the iterator's constructor to require a collection.
You didn't provide a concrete example, but if the class reminds you of goto, it probably is a bad idea.
You said the new object must interrogate the instantiating object for information. Perhaps the class makes too many assumptions about its environment? If those assumptions complicate unit testing, debugging, or (non-hypothetical) code reuse, then you should consider refactoring.
But if the design saves developer time overall and you don't expect an unmaintainable beast in two years' time, the practice is completely acceptable from a practical standpoint.

Don't static members make classes kind of (global) objects themselves?

Every time I come across an implementation of the singleton pattern or any static classes (i.e. classes with (almost) only static members) I wonder whether this isn't actually a hack and therefore heavy abuse of the principle of classes and instances just to design single objects instead of designing classes and creating a single instance. To me, it looks like static members of classes in general try to add some sort of characteristics to classes which they actually aren't supposed to have and which rather make them object themselves.
But is it really desirable to have single objects implemented like that?
Or do you see things completely differently and don't think that such static classes or singletons have anything in common with actual objects?
Static members are effectively just namespacing for globals, yes. Nothing wrong with that; namespacing is good, and globals are the cleanest way to accomplish some tasks.
Singletons can be somewhat more interesting (load on demand...) but they're a similar construct (yeah, you could think of a static member as an anonymous singleton managed by the compiler).
Like most things, these tools have their place, and only the ideologues worry about whether or not they "fit" with a particular ideology.
Depending on your language, classes are objects. In ruby and java, they're of class Class; in python, I don't remember (subclasses of type?).
In java, you can't avoid putting things on classes. This means you sometimes have to use classes like you would use namespaces and modules. A lot of the static methods on Math are a good example of this. I'd say that having these methods be static makes the best of a bad situation.
I think whether it's "dirty" to have static attributes depends very much on the context. What you really should look for is proper encapsulation: it's good if you can draw a curve through the conceptual space of your code and say "everything on this side doesn't need to know anything about things on that side, except for the interface across the curve.
You can view it from a performance and memory perspective. For example, in the following code:
public class StringUtils
{
public static boolean isEmpty(String value)
{
// some code
}
public static String reverseString(String value)
{
// some code
}
}
Do you really want to instantiate StringUtils objects all over the place just to call a method that doesn't store any member variables? In a simple program, it doesn't matter much. But once your program starts to get to a certain size and you call these methods thousands of times, well let's just the instantiations can add up. And why? To be a purist? It's not worth the cost. Just use the same instance.
Say I have an application which has a single configuration file. How would I create functions to operate on that file without the use of a "singleton" if my language does not support global functions outside of a class (like Java or C#)?
It seems to me the only real way to accomplish that is have a singleton class. Using the singleton pattern you also don't need to pass around a pointer to the object, since you can just use the static method to get it again.
I don't see how this is a violation of any OO principles. To do it a different way, like put the configuration functions in another class that doesn't deal with configuration (like a "utility" class) is more of a violation of OO principles.
Suppose that you have a multi-threaded application which requires a central data repository. The consumers and producers use or put data in the repository, including the external application object which accesses the repository through an interface.
If you made this repository a normal class object, you'd have the problem of initializing it and getting a pointer to every object that needed it. Not the toughest problem, but it can be very confusing with a lot of threads and objects.
On the other hand, if you do this:
public enum Data implements MyInterface{
INSTANCE;
private final Whatevertype secretstuff = new Whatevertype();
...etc...
public void PutThing( Sometype indata){ ... };
public Sometype GetThing( int somecode ){ ...};
...etc...
}
You (a) don't have to instantiate anything and (b) can access from anywhere with
Data.INSTANCE.GetThing(42);
etc. It's just like Highlander... THERE CAN ONLY BE ONE