Buzzword Buster – Macaroni Code

Definition:

You have Macaroni code when your application is chopped up into many little pieces and it’s difficult to see the big picture which may exist only in your (or someone else’s!) head.

In software design, you can often end up with Macaroni code when you overuse/misuse/abuse abstractions, and it’s one of the main dangers of using Inversion of Control.

image

Buzzword Buster – IoC

Definition:

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.

Purpose:

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:

  • decoupling of execution of a task from implementation (through the use of interfaces)
  • greater separation of concerns (each component only focuses on what it’s designed to do)
  • more flexibility (implementation can be easily changed without any side effects on other components)
  • more testable code (enables the use of stubs/mocks in place of concrete classes intended for production)

Advantages:

  • Simplifies the building of specific tasks.

Disadvantages:

  • Has the potential to make the flow of control in an application more complex, and therefore making it harder to follow.

Parting thoughts..

  • Misusing or abusing IoC can result in Macaroni code.
  • IoC is not a silver bullet for all your system engineering problems, and remember, "Don’t fix what’s not broken"
  • When adopting IoC, there is additional training needs for new joiners to the team.
  • Design systems for flexibility, which allows quick adaptation to changing environment/requirementsimage
  • Avoid complicating system design by trying to be future-proof upfront, you can’t predict the future! image

Further readings:

.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)

Testing with Pex

Some time ago I read about (might be on DotNetRocks) a little gem coming out of Microsoft’s research lab called Pex, which is a framework for doing automated White Box Testing in .Net. It’s still in its early days (despite having been around for more than 2 years now) but packs a bag of potential judging by what I’ve seen of the demo materials and been able to use myself!

In short, Pex is able to analyze your methods and work out the boundary conditions, etc. and derive a series of tests that can be used to test your method with as high a coverage as possible. The download package also includes a lightweight framework for test stubs and detours (which basically allows you to replace any .Net method with your own delegate) called Stubs and Moles. It also comes with the ability to automatically generate test project for you in MSTest and NUnit though I haven’t tested out the NUnit generation as it didn’t support NUnit generation the last time I played around it.

I won’t go into detail on how to use it as there are a ton of documentation and demo material on its site and I have barely scratched the surface myself, but do check it out if you haven’t done so already!

DataContract Serialization by Reference using the IsReference Property

I came across this blog post the other day which introduced to me a cool addition to the DataContract serializer – the ability to generate XML by reference rather than by value:

http://www.zamd.net/2008/05/20/DataContractSerializerAndIsReferenceProperty.aspx

Not much for me to add to it really, just read the blog to see how it works.

Dealing with Circular References in WCF

Using entity classes in your application and WCF is complaining about the circular references between your classes? Well, I had the exact same problem not long ago, and I found this post on James Kovac’s blog about circular references and how to get around them:

http://www.jameskovacs.com/blog/GoingAroundInCirclesWithWCF.aspx

The key things to note from this post is that:

  1. WCF can handle circular references, but is not switched on by default
  2. There is a boolean flag in the constructor for the DataContractSerializer class which enables object references to be preserved
  3. We can tell WCF to switch this on by deriving from the DataContractSerializerOperationBehaviour class (as shown in the blog post above)

By this point you’re probably wondering why circular reference handling is not enabled by default, according to James Kovac, it’s because WCF by default tries to respect interoperability safety:

Now why can’t WCF handle circular references out-of-the-box. The reason is that there is no industry-accepted, interoperable way of expressing anything but parent-child relationships in XML. You can use the ID/IDREF feature of XML or the key/keyref feature of XML Schema, but a lot of serializers don’t respect these attributes or handle them properly. So if you want to serialize circular references, you need to stray out of the realm of safe interoperability.

So here are the classes you need to create to extend DataContractSerializerOperationBehaviour in order to preserve object reference:

public class PreserveReferencesOperationBehavior : DataContractSerializerOperationBehavior
{
     public PreserveReferencesOperationBehavior(OperationDescription operation) : base(operation)
     {
     }

     public PreserveReferencesOperationBehavior(
          OperationDescription operation, DataContractFormatAttribute dataContractFormatAttribute)
          : base(operation, dataContractFormatAttribute)
     {
     }

     public override XmlObjectSerializer CreateSerializer(
          Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
     {
          return new DataContractSerializer(type, name, ns, knownTypes,
                                            0x7FFF /*maxItemsInObjectGraph*/,
                                            false/*ignoreExtensionDataObject*/,
                                            true/*preserveObjectReferences*/,
                                            null/*dataContractSurrogate*/);
     }
}

And the attribute to use on your operation contract:

public class PreserveReferencesAttribute : Attribute, IOperationBehavior
{
     public void AddBindingParameters(OperationDescription description,
                                      BindingParameterCollection parameters)
     {
     }

     public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
     {
          IOperationBehavior innerBehavior = new PreserveReferencesOperationBehavior(description);
          innerBehavior.ApplyClientBehavior(description, proxy);
     }

     public void ApplyDispatchBehavior(OperationDescription description,
                                       DispatchOperation dispatch)
     {
          IOperationBehavior innerBehavior = new PreserveReferencesOperationBehavior(description);
          innerBehavior.ApplyDispatchBehavior(description, dispatch);
     }

     public void Validate(OperationDescription description)
     {
     }
}

which you apply like this:

[OperationContract]
[PreserveReferences]
MyClass RetrieveMyClass();