This is so good I keep going back to it, so to save myself and you the hassle of searching for it every time I thought I’d share it here on my blog, enjoy! ![]()
This is so good I keep going back to it, so to save myself and you the hassle of searching for it every time I thought I’d share it here on my blog, enjoy! ![]()
We’ve all been there before, write a simple service with a simple method:
[ServiceContract]
public interface IService
{
[OperationContract]
int SimpleMethod(object param1);
}
As time goes by, the simple method gets more complicated, and the list of parameters grows and eventually simple method is overloaded to provide more variety and simple method is simple no more!
A simple solution to this is the Request-Response pattern, by encapsulating all the input and output values into request and response objects you will be able to:
And you’ll be able to do all this without even changing the service contract!
[ServiceContract]
public interface IService
{
[OperationContract]
SimpleMethodResponse SimpleMethod(SimpleMethodRequest request);
}
[DataContract]
public void SimpleMethodRequest
{
[DataMember]
public object Param1 { get; set; }
[DataMember]
public string Param2 { get; set; }
[DataMember]
public int Param3 { get; set; }
…
}
[DataContract]
public void SimpleMethodResponse
{
[DataMember]
public bool Success { get; set; }
[DataMember]
public int? ErrorCode { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
…
}
In addition, you can also create a hierarchy of request/response objects and consolidate your validation logic in validator classes or custom validation attractions (you can use PostSharp to write attributes that take care of the validation ‘aspect’ of your application).
If you’ve used events in C# before, you’ve probably written code like this too:
public event EventHandler Started;
...
// make sure Started is not null before firing the event
// else, NullReferenceException will be thrown
if (Started != null)
{
Started(this, some_event_args);
}
This is perfectly ok and normal to do, but can quickly become tiresome if you have to fire events in multiple places in your code and have to do a null reference check every time!
So instead, I have been using this pattern for a while:
// initialise with empty event hanlder so there's no need for Null reference check later
public event EventHandler Started = (s, e) => { };
...
// no need for Null reference check anymore as Started is never null
Started(this, some_event_args);
If all you need is the ability to add/remove handlers, then this pattern would do you fine as the event will never be null because there’s no way for you to remove the anonymous method the event was initialised with unless you set the event to null.
However, if you occasionally need to clear ALL the event handlers and set the event to null, then don’t use this pattern as you might start seeing NullReferenceException being thrown before you add event handlers back in.
Inversion of Control (IoC) refers to the inversion of the flow of control (the order in which individual statements, function calls, etc. are executed) in a software. You’ll often hear the term Hollywood principle being mentioned in the same breath as IoC, it simply states “Don’t call us, we’ll call you” which more or less sums up the principles of IoC.
In traditional software design, the flow of control is governed by a central piece of code which often have to address multiple concerns (logging, validation, etc.) and need to be aware of the implementation details of its dependencies. This creates a very tightly coupled application where changes in one component have a ripple effect throughout the rest of the application.
Following the principles of IoC can help you achieve:
.NetRocks show 362 — James Kovac Inverts our Control!
Loosen Up — Tame Your Software Dependencies For More Flexible Apps (MSDN article by James Kovac)
Design Pattern — Inversion of Control and Dependency Injection (by Shivprasad Koirala)
The Dispose pattern is something we’ve all seen before, and it’s so tried and tested most of us (especially myself!) have been more than happy to apply without question.
Whilst reading various blogs/articles I came across some differing opinion about this well known pattern and started to question what I had taken for granted myself.
After some more research and a question on the goldmine of knowledge that is the StackOverflow I have shortlisted a few points you should consider when implementing the standard C# dispose pattern:
So for a simple class with no unmanaged resources and a collection of IDisposable objects, your class might look something like this:
public sealed class MyClass : IDisposable
{
IList<MyObject> objects; // MyClass holds a list of objects
private bool _disposed; // boolean flag to stop us calling Dispose(twice)
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
// call Dispose on each item in the list
if (disposing)
{
foreach (var o in objects)
{
// check if MyObject implements IDisposable
var d = o as IDisposable();
if (d != null) d.Dispose();
}
}
_disposed = true;
}
}
}
This is fairly similar to the standard C# Dispose pattern, the main difference being the lack of a finalizer because remember, implementing a finalizer will impact the performance of your type so don’t implement it unless you need it.