views:

117

answers:

2

I have been very intriuged by design patterns lately, and specifically following correct design patterns in my classes that implement one or several interfaces.

Let's take an example. When a class implement IDisposable you should follow a specific pattern to make sure that your resources are properly cleaned up, by creating a private Dispose(bool disposing) method that differentiates between if it's called by the finalizer, or if it's called from the public Dispose method. Also, a finalizer should be implemented in this case, and you might also need a private bool variable called isDisposed that is set by the Dispose method, so that any method called after th object is Disposed will call a Exception making it clear that this object is already disposed, instead of the code inside the method crashing because some of the required resouces are disposed, and thereby no longer available.

There are also a lot of other interfaces I routinely implement, but it's not all of them I am sure if the way I implement them is the preferred way of doing it, and I might find out later on that it causes a subtle bug that is hard to find, that would probably have been non-existant if I had followed the proper pattern in the first place.

some examples of interfaces I would like to know the best way of implementing are ISerializable, IComparable, IComparable<>, ICloneable, IEnumerable<>, and so on. All interfaces from the Framework are interesting here, so it should not be limited to those I have listed above.

What I'm after is for different interfaces, the preferred way and hopefully also a link to resource on the internet that explains how and also why a specific pattern should be followed.

I hope to get a good collection of these patterns, as I know that they can greatly improve my code and make it more correct, and follow best-practices

It would be great if there are several patterns for the same interface so we can discuss which one is preferred. That might also cause some of you to maybe move over to a new pattern, or make modifications to your existing patterns to improve your code even further, and that would be great!

Edit

After reading Grzenios comment, I would also urge everyone to give the context the pattern should be applied for. For example the IDIsposable pattern should only be followed if you have some unmanaged resources inside your class that you need to dispose, and not if all the objects you need to dispose implements IDisposable themselves.

Edit 2

I should probably start this myself, since I put the question out here. So I'll describe one pattern I know well, and that is the IDisposable pattern.

This pattern should only be used if your class contain one or more unmanaged resources inside your class, and you hav eto make sure that they get Disposed. in this case in addition to the Dispose method we will need a finalizer in case the user of your class forget to dispose it.

So first thing first. Your class should implement the IDisposable interface, and you will have to define the public Dispose method as goverend by the interface. This method should look like this:

public void Dispose()
{
  Dispose(true);
  GC.SuppressFinalize(this);
}

This will call the protected Dispose(bool) method that takes care of the actual cleanup.

Also, include a vaiable in your class to indicate if the class is disposed or not:

private bool alreadyDisposed = false;

GC.SuppressFinalize tells the garbage collector that this item does not need to be finalized even if it has a finalizer.

Then you need the protected Dispose method. Make it protected instead of private in case any derived class needs to override it:

protected virtual void Dispose(bool isDisposing)
{
  if (alreadyDisposed)
  {
    return;
  }
  if (isDisposing)
  {
    // free all managed resources here
  }
  // free all unmanaged resources here.
  alreadyDisposed = true;
}

The finalizer should also call Dispose(bool) if the user forgets to clean up:

~SomeClass(){
  Dispose(false);
}

If some method require a disposed resource to function, make the function like this:

public void SomeMethod()
{
  if (alreadyDisposed)
    throw new ObjectDisposedException("SomeClass",
                                      "Called SomeMethod on Disposed object");
  // Method body goes here
}

That's it. This will make sure that the resources gets cleaned up. Preferable by the user of your class calling Dispose, but by adding a Finalizer as a fallback method.

A: 

For example the IDIsposable pattern should only be followed if you have some unmanaged resources inside your class that you need to dispose, and not if all the objects you need to dispose implements IDisposable themselves.

I disagee with the above. I never recommend allowing the GC to do clean up and be implicit about object and resource disposal. It's kind of like waiting for the maid to come around and pick up your wet towels at a hotel; it will happen eventually, but the right thing to do is pick them up and hang them up yourself.

Deterministic disposal of objects and keeping scope of those resources as minimal as possible will make for the leanest and most efficient applications, not to mention that for developers reading the code, it is much more explicit to dispose of resources and reads better. Like a beginning and an end to a story that one can see all in one place. I instantiate the object as late as possible and dispose of it as soon as possible after use minimizing scope. Either explicitly calling .Dispose on the object or utilizing a Using block that calls the .Dispose method automatically are (2) good ways of cleaning up.

There are also a lot of other interfaces I routinely implement, but it's not all of them I am sure if the way I implement them is the preferred way of doing it, and I might find out later on that it causes a subtle bug that is hard to find, that would probably have been non-existant if I had followed the proper pattern in the first place.

The entire purpose of an Interface is to create a guidline for the methods, properties, events, etc. that a class is to implement, but not provide the details on how to do it. That is up to you. There is no "pattern" per se of how to implement specefic Interfaces. Don't get thrown off by the IDisposable Interface. Upon creating the Interface in VS.NET, the plumming code is created for you which is not typical for an Interface, and in reality could be completely changed to what you need.

I think where you might be getting confused is about Implementing Interfaces that are in the .NET Framework, but you need to look at the concept of an Interface and not just the ones available in the Framework. If you really want to see examples of how the Interfaces in the .NET Framework are implemented, look at either the MSDN or decompile other Framework objects that implement those Interfaces to see how Microsoft implements them.

As you grow in OOD, you will begin to see the power behind interfaces and begin to create them for your classes. For example lets say you have an interface named IMachine with a method called .StartEngine(). We just want the implementer of the Interface to define all of the details themself; there is no 'pattern' to follow and we the Interface designer don't need to know or care how it is implemented. For a car maybe the methods implementation involves "Get the keys, place them in the ignition, put in park, press brake pedal, turn ignition..." However for a lawnmower the same methods implementation is "Put gass in the mower, prime the carborateor, pull the clutch, pull the cord..."

So you see you can't just look at Interfaces by the ones in the .NET Framework and how to apply a certain pattern to thier implementation. The implementation details, patterns, etc. are up to the implementing class, and as long as the details of the Interface are sufficed, then thats what matters.

Hope this helps a bit...

atconway
This is quite wrong. Interfering with the GC causes inefficiencies in the general case, since both the .NET runtime and the C# compiler are optimised for the default case. So, unless you have a good reason (such as releasing unmanaged resources), it is usually better to avoid disposing objects manually.
Gorpik
I see where you are going with this, and I understand the power of interfaces quite well. But I guess that some of the more standard interfaces of the framework usually gets implemented in quite the same way most of the times, at least I guess that some guidelines apply each time you implement it. Like I guess that for ISerializable there are some practices you should follow that makes serialization safer than it would if you don't follow them.
Øyvind Bråthen
@Gorpik - We are going to have to agree to disagree, because deterministic object disposal is NOT wrong. Instantiating objects and not calling .Dispose() on them and minimizing the scope to me is sloppy programming and inefficient. This does not interefer with GC, it just speeds up the process. This is why you make the call 'GC.SuppressFinalize(Me)' in the dispose method to flag GC not to call the Finalize method on this object because it has already been done.
atconway
+2  A: 

While you're learning about design patterns, you should also look at some common anti-patterns, you get an idea where the pattern comes from. IDisposable is somewhat of an anti-pattern, a minor version of sequential coupling, in that it requires a user to call dispose, and if he forgets, you're in the shit. One of the main reasons of the "disposable pattern" is to fix this issue.

A preferred technique (of mine anyway), wherever possible, is not to expose an IDisposable object to a user, but expose a single method (call it Using(...) for example), which takes a delegate which would execute the code normally contained in your using(...) { } block. This method can perform your construction, execute the delegate, then dispose the resources it consumed, and omits at least 3 problems with IDisposable: That of the user forgetting to call it, the user calling it more than once, and the user calling it too early - you don't need to bother with that boilerplate "disposable pattern" when there's no IDisposable exposed.

An example, lets say I have a File IO requirement where I need to open the same files regularly (and thus, I can't be waiting on the garbage collector to call Finalize in the event that a user forgets to call Dispose).

class MyFileStream {
    FileStream fs;
    private MyFileStream(string filename, FileMode mode) {
        fs = new FileStream(filename, FileMode.Open);
    }
    private void Dispose() {
        fs.Dispose();
    }
    public static void Using(string filename, FileMode mode, Action<MyFileStream> use) {
        MyFileStream mfs = new MyFileStream(filename, mode);
        use(mfs);
        mfs.Dispose();
    }
    public void Read(...) { ... }
}

A caller can then say

var x = default(...);
MyFileStream.Using("filename.txt", FileMode.Open, (stream) => {
    x = stream.Read(...);
});
Console.WriteLine(x);

Note that this is rather similar to the using() { } language syntax anyway, only this time you are forced to use it, and it imposes further restrictions. One cannot forget to clear up the resources this way.

Still, this pattern isn't always suitable because you sometimes need the resources to last longer than just a method call or so, but if you find the opportunity to use it, do so.

I've completely gone off topic anyway, so back to what you were asking.

  • Do not use ICloneable - it says nothing about how an object is being cloned (deep or shallow), if you require such thing, create your own IDeepCloneable or IShallowCloneable interfaces instead.
  • For IEnumerable<>, it's a rare event that you need to create your own, because there's a rather large collection of existing classes in the framework already, and you can usually get additional features much more simply by implementing extension methods (Such as those in LINQ, or your own, making use of the powerful yield keyword, which will create an IEnumerable<> for you in the background).

I wouldn't say there's any specific pattern for the rest, they're pretty self explanatory.

Mark H