This is so good I keep going back to it, so to save myself and you the has­sle of search­ing for it every time I thought I’d share it here on my blog, enjoy! Smile

Share

We’ve all been there before, write a sim­ple ser­vice with a sim­ple method:

[ServiceContract]
public interface IService
{
    [OperationContract]
    int SimpleMethod(object param1);
}

As time goes by, the sim­ple method gets more com­pli­cated, and the list of para­me­ters grows and even­tu­ally sim­ple method is over­loaded to pro­vide more vari­ety and sim­ple method is sim­ple no more!

A sim­ple solu­tion to this is the Request-Response pat­tern, by encap­su­lat­ing all the input and out­put val­ues into request and response objects you will be able to:

  • solve the prob­lem with grow­ing parameters
  • have an easy way of pro­vid­ing mul­ti­ple results
  • add input/output val­ues incrementally

And you’ll be able to do all this with­out even chang­ing the ser­vice 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 addi­tion, you can also cre­ate a hier­ar­chy of request/response objects and con­sol­i­date your val­i­da­tion logic in val­ida­tor classes or cus­tom val­i­da­tion attrac­tions (you can use Post­Sharp to write attrib­utes that take care of the val­i­da­tion ‘aspect’ of your application).

Ref­er­ences:

API Design Pat­terns – Request/Response

Share

If you’ve used events in C# before, you’ve prob­a­bly writ­ten 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 per­fectly ok and nor­mal to do, but can quickly become tire­some if you have to fire events in mul­ti­ple places in your code and have to do a null ref­er­ence check every time!

So instead, I have been using this pat­tern 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 abil­ity to add/remove han­dlers, then this pat­tern would do you fine as the event will never be null because there’s no way for you to remove the anony­mous method the event was ini­tialised with unless you set the event to null.

How­ever, if you occa­sion­ally need to clear ALL the event han­dlers and set the event to null, then don’t use this pat­tern as you might start see­ing Null­Ref­er­ence­Ex­cep­tion being thrown before you add event han­dlers back in.

Share

Def­i­n­i­tion:

Inver­sion of Control (IoC) refers to the inver­sion of the flow of con­trol (the order in which indi­vid­ual state­ments, func­tion calls, etc. are exe­cuted) in a soft­ware. You’ll often hear the term Hol­ly­wood prin­ci­ple being men­tioned in the same breath as IoC, it sim­ply states “Don’t call us, we’ll call you” which more or less sums up the prin­ci­ples of IoC.

Pur­pose:

In tra­di­tional soft­ware design, the flow of con­trol is gov­erned by a cen­tral piece of code which often have to address mul­ti­ple con­cerns (log­ging, val­i­da­tion, etc.) and need to be aware of the imple­men­ta­tion details of its depen­den­cies. This cre­ates a very tightly cou­pled appli­ca­tion where changes in one com­po­nent have a rip­ple effect through­out the rest of the application.

Fol­low­ing the prin­ci­ples of IoC can help you achieve:

  • decou­pling of exe­cu­tion of a task from imple­men­ta­tion (through the use of interfaces)
  • greater sep­a­ra­tion of con­cerns (each com­po­nent only focuses on what it’s designed to do)
  • more flex­i­bil­ity (imple­men­ta­tion can be eas­ily changed with­out any side effects on other components)
  • more testable code (enables the use of stubs/mocks in place of con­crete classes intended for production)

Advan­tages:

  • Sim­pli­fies the build­ing of spe­cific tasks.

Dis­ad­van­tages:

  • Has the poten­tial to make the flow of con­trol in an appli­ca­tion more com­plex, and there­fore mak­ing it harder to follow.

Part­ing thoughts..

  • Mis­us­ing or abus­ing IoC can result in Mac­a­roni code.
  • IoC is not a sil­ver bul­let for all your sys­tem engi­neer­ing prob­lems, and remem­ber, “Don’t fix what’s not broken”
  • When adopt­ing IoC, there is addi­tional train­ing needs for new join­ers to the team.
  • Design sys­tems for flex­i­bil­ity, which allows quick adap­ta­tion to chang­ing environment/requirementsimage
  • Avoid com­pli­cat­ing sys­tem design by try­ing to be future-proof upfront, you can’t pre­dict the future! image

Fur­ther readings:

.NetRocks show 362 — James Kovac Inverts our Control!

Loosen Up — Tame Your Soft­ware Depen­den­cies For More Flex­i­ble Apps (MSDN arti­cle by James Kovac)

Design Pat­tern — Inver­sion of Con­trol and Depen­dency Injec­tion (by Shiv­prasad Koirala)

Share

The Dis­pose pat­tern is some­thing we’ve all seen before, and it’s so tried and tested most of us (espe­cially myself!) have been more than happy to apply with­out question.

Whilst read­ing var­i­ous blogs/articles I came across some dif­fer­ing opin­ion about this well known pat­tern and started to ques­tion what I had taken for granted myself.

After some more research and a ques­tion on the gold­mine of knowl­edge that is the Stack­Over­flow I have short­listed a few points you should con­sider when imple­ment­ing the stan­dard C# dis­pose pattern:

  1. if your object doesn’t hold any IDis­pos­able objects or unman­aged resources (DB con­nec­tion, for exam­ple) then you don’t need to imple­ment the IDis­pos­able or final­izer at all
  2. if your object doesn’t hold any unman­aged resources then don’t imple­ment a final­izer, the Garbage Col­lec­tor won’t attempt to final­ize your object (which has a per­for­mance hit) unless you have imple­mented a finalizer.
  3. don’t for­get to call Dis­pose() on each of the IDis­pos­able objects in the Dispose(bool) method.
  4. if your object holds unman­aged resources, clean them up in the final­izer with­out re-writing any of the cleanup code in the Dispose(bool) method already.

So for a sim­ple class with no unman­aged resources and a col­lec­tion of IDis­pos­able objects, your class might look some­thing 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 sim­i­lar to the stan­dard C# Dis­pose pat­tern, the main dif­fer­ence being the lack of a final­izer because remem­ber, imple­ment­ing a final­izer will impact the per­for­mance of your type so don’t imple­ment it unless you need it.

Share