maandag 25 februari 2013

DTO's with parameterized constructors

At my current project we use dto's to transfer data from an MVC.Net controller to the domain services, like this:

public class HomeController : Controller
{
   public ActionResult Index()
   {
      var dto = new SomeDto();
      dto.SomeValue = "foo";

      var domainService = new DomainService();
      domainService.DoSomething(dto);
   }
}


One problem with the CustomDto is that is doesn't coerce that the SomeValue property is filled. We can do this, and the compiler says it's ok:


var dtonew CustomDto();
// dto.SomeValue = "foo";

var domainServicenew DomainService();
domainService.DoSomething(dto);

Ofcourse when we run the code we will get an exception if domainService.DoSomething expects the dto.SomeValue to not be null.

The real danger

The real danger of not having a constructor with paramaters is this:

We have the DomainService:



public class DomainService
{
   public void DoSomething(SomeDto dto)
   {
      // pseudo: do something with dto.SomeValue
   }
}

And we have a unit test:


[TestClass]
public class Tests
{
   [TestMethod]
   public void Test1()
   {
      var dto = new SomeDto();
      dto.SomeValue = "foo";

      var domainService = new DomainService();
      domainService.DoSomething(dto);
   }
}


Now we decide that for DoSomething to work, it needs an extra property on SomeDto:, so we add SomeOtherValue:


public class SomeDto
{
   public string SomeValue{get;set;}
   public string SomeOtherValue{get;set;}
}


And we add that to the unit test:



[TestClass]
public class Tests
   {
      [TestMethod]
      public void Test1()
      {
         var dto = new SomeDto();
         dto.SomeValue = "foo";
         dto.SomeOtherValue = "bar";

         var domainService = new DomainService();
         domainService.DoSomething(dto);
   }
}

And we change the implementation of DoSomething:

public class DomainService
{
   public void DoSomething(SomeDto dto)
   {
      // pseudo: do something with dto.SomeValue
      // pseudo: and we do something with dto.SomeOtherValue
   }
}

Is we compile the code, it will succeed. If we run the test it will succeed. But it's not untill we start debugging or deploy the code that we find out that the code is broken, because the Index method of the HomeController doens't supply SomeOtherValue to the dto.

Fortunately there's an easy solution to this problem, and that is:


A constructor with parameters



public class SomeDto
{
   public SomeDto(string someValue, string someOtherValue)
   {
      SomeValue = someValue;
      SomeOtherValue = someOtherValue;
   }

   public string SomeValue{get;set;}
   
   public string SomeOtherValue{get;set;}
}

(You can also as an addition choose to make the setters not public.)

Now we have to change our test like this:




[TestClass]
public class Tests
{
   [TestMethod]
   public void Test1()
   {
      var dto = new SomeDto("foo", "bar");

      var domainService = new DomainService();
      domainService.DoSomething(dto);

   }
}

If we compile the code the compiler returns an error, because the  Index method of the HomeController doesn't use the constructor. So we have to change that code too:


public class HomeController : Controller
{
   public ActionResult Index()
   {
      var dto = new SomeDto("foo", "???");

      var domainService = new DomainService();
      domainService.DoSomething(dto);
   }
}


Conclusion

Using a parameterized constructor protects us against overlooking parts of code that has to be changed when making changes to other parts.

donderdag 21 februari 2013

Fluent builder pattern

In this article we'll see how we can construct an object in a fluent way. This pattern is called Fluent Builder or Fluent interface.

In the previous article I've refactored a class that does too much, into a class that does one thing (Single Responsibility Principle). Now we take a look at how we can improve a specific part of the code with the Fluent Builder pattern.

This is the class we start with:


public class SourceXDocumentCreator
{
   public XDocument AddMetadata(XDocument xdoc, string metadata)
   {
      // Add metadata to XDocument
      // return XDocument
   }

   public XDocument AddHeader(XDocument xdoc, string title)
   {
      // Add header with title  to XDocument
      // return XDocument
   }

   public XDocument AddLogo(XDocument xdoc, string name,
                            double width, double height)
   {
      // Add logo to XDocument
      // return XDocument
   }

   // etc.
}

If we call this class to create a SourceXDocument, it could look like this:

var xdoc = GetXDocumentById(1);
var creator = new SourceXDocumentCreator();
xdoc = creator.AddMetadata(xdoc, metadata);
xdoc = creator.AddHeader(xdoc, "This is the title");
xdoc = creator.AddLogo(xdoc, "name", 7.2, 4.3);

As you can see every first variable of each method call is xdoc. If we need that variable in each method, we can just as well add it to the constructor of SourceXDocumentCreator:

public class SourceXDocumentCreator
{
   private XDocument _xdoc;

   public SourceXDocumentCreator(XDocument xdoc)
   {
      _xdoc = xdoc;
   }

   public XDocument AddMetadata(string metadata)
   {
      // Add metadata to _xdoc
      // return _xdoc
   }

   public XDocument AddHeader(string title)
   {
      // Add header with title to _xdoc
      // return _xdoc
   }

   public XDocument AddLogo(string name, double width,
                            double height)
   {
      // Add logo to _xdoc
      // return _xdoc
   }

   // etc.
}

Now we have the private variable _xdoc, it's not neccesary anymore to pass xdoc to each and every method. And we can use SourceXDocumentCreator like this:

var xdoc = GetXDocumentById(1);
var creator = new SourceXDocumentCreator(xdoc);
xdoc = creator.AddMetadata(metadata);
xdoc = creator.AddHeader("This is the title");
xdoc = creator.AddLogo("name", 7.2, 4.3);

This looks a lot cleaner, but still we can reduce the amount of code we need. We actually only need the final xdoc, and not semi-finished product:

var xdoc GetXDocumentById(1);
var creator = new SourceXDocumentCreator(xdoc);
creator.AddMetadata(metadata);
creator.AddHeader("This is the title");
xdoc = creator.AddLogo("name", 7.2, 4.3);

And now only the creator variable is redundant. But we can reduce that too, like this:

var xdoc GetXDocumentById(1);
var creator = new SourceXDocumentCreator(xdoc)
   .AddMetadata(metadata)
   .AddHeader("This is the title")
   .AddLogo("name", 7.2, 4.3)
   .Build();

For the code above to work, we have to change our SourceXDocumentCreator class, so each of the 'add'-methods returns the current instance of SourceXDocumentCreator:


public class SourceXDocumentCreator
{
   private XDocument _xdoc;


   public SourceXDocumentCreator(XDocument xdoc)
   {
      _xdoc = xdoc;
   }

   public SourceXDocumentCreator AddMetadata(string metadata)
   {
      // Add metadata to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddHeader(string title)
   {
      // Add header with title to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddLogo(string name,
                                         double width,
                                         double height)
   {
      // Add logo to _xdoc
      return this;
   }

   public XDocument Build()
   {
      return _xdoc;
   }

}

Because each Add-method returns and instance of SourceXDocumentCreator, we can call another Add-method on it again:


var creator = new SourceXDocumentCreator(xdoc)
   .AddMetadata(metadata)
   .AddHeader("This is the title");

And we can continue to call some other methoda:

creator = creator
   .AddLogo("name", 7.2, 4.3)
   .WithSomethingElse()
   .AndAnotherThing()
   .ThisToo();

But how do we get the final XDocument of each method returns an instance of SourceXDocumentCreator? for this, we add a public Build method, which returns the _xdoc variable. And to complete that class, we rename it to SourceXDocumentBuilder, to express better that the fluent builder  pattern is used.

This is the final SourceXDocumentBuilder:


public class SourceXDocumentBuilder
{
   private XDocument _xdoc;

   public SourceXDocumentCreator(XDocument xdoc)
   {
      _xdoc = xdoc;
   }

   public SourceXDocumentCreator AddMetadata(string metadata)
   {
      // Add metadata to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddHeader(string title)
   {
      // Add header with title to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddLogo(string name,
                                         double width,
                                         double height)
   {
      // Add logo to _xdoc
      return this;
   }

   public XDocument Build()
   {
      return _xdoc;
   }
}


dinsdag 19 februari 2013

Single responsibility principle


At the current project I'm working on we've made a class with one of the most meaningless names I've ever encountered: Preprocessor. It's used to combine different parts of xml into a final xml document, but you probably can not tell that by the name of it. This class has two problems that I'll write about: it has a bad name, and it does too much so we couldn't find a good name for it.

public class Preprocessor
{
   public PreprocesResult Proces(PreprocesInput preprocesInput)
   {
   }
}


Preprocessor is a bad name for our class, because it doesn't mean anything in our domain. If we were building a system that had something to do with audio or video, then preprocessor maybe wouldn't be a terrible name. But we are building a system that manages documents and publications and the workflow involved. And the name preprocessor doesn't say anything about what is being processed, or how, or what the output will be. Is it preprocessing documents, or publications or something else?

XmlPreprocessor would be a better name. Still not good, but at least it would say what is being processed.

If multiple parts of xml would be put together, then XmlJoiner would be a better name, or XmlCombiner.

Why couldn't we choose a good name for our class? Because this class does too much. This is a list of things the class does when you call the Process() merhod:


  • Add Metadata to the given XML document;
  • Add header element to the given XML document;
  • Get all referenced to images from content, get image data from database and disk;
  • Calculate width/height ratio from image;
  • Change image-values in the given XML document;
  • Get organisation that created the given XML document;
  • Get logo image of organisation, save to temp folder and save reference to database;
  • Calculate width/height ratio from image;
  • Add Logo-element to the given XML document;
  • Get XSL file from disk;
  • Execute XSL transformation on the given XML document;
  • Save final version of the created XML document to temp folder and save reference to database.

As you can see the class does quite a few different things. Some are related to xml, some are related to getting data from disk or a database and some are related to calculating things like width/height ratio. And all are necessary to create the final XML document. But not all things should be put in one class. Let's look at every function of the class that is really related to modifying XML:


  • Add Metadata to XML;
  • Add header element to XML;
  • Get organisation that created the document;
  • Get logo image of organisation, save to temp folder and save reference to database;
  • Calculate width/height ratio from image;
  • Add Logo-element to XML;
  • Get all referenced to images from content, get image data from database and disk;
  • Calculate width/height ratio from image;
  • Change image-values in XML;
  • Get XSL file from disk;
  • Execute XSL transformation;
  • Save final version of XML to temp folder and save reference to database;


Now that we've identified the functions that are related to XML we can put them into another class:

public class SourceXDocumentCreator
{
   public XDocument AddMetadata(XDocument xdoc, string metadata)
   {
      // Add metadata to XDocument
      // return XDocument
   }

   public XDocument AddHeader(XDocument xdoc, string title)
   {
      // Add header with title  to XDocument
      // return XDocument
   }

   public XDocument AddLogo(XDocument xdoc, string name,
                            double width, double height)
   {
      // Add logo to XDocument
      // return XDocument
   }

   // etc.
}

The name is much better now, as it clearly states that the class can be used to create some Source XML Document. (There probably are alternatives that are even better.)

If we ever need to extend or modify the SourceXDocumentCreator class, it's much easier to decide how to do it. As it's evident that saving or loading files from disk or database shouldn't be in there, opposed to the first class Preprocessor, which did exactly that and much more.
Also calculating ratio's doesn't belong in SourceXDocumentCreator.
But adding an element to the underlying XDocument does belong in the SourceXDocumentCreator class. And so does the function of changing a specific value in the underlying XDocument. 

Conclusion
This article showed that gving a class a good name, and making sure that a class doesn't do too much (does only one thing), helps in making it easier to decide if and how to modify it.

For more information about the Single Responsibility principle see:
http://en.wikipedia.org/wiki/Single_responsibility_principle

dinsdag 5 februari 2013

XML Serialization with C# (update)

This is now my preferred way to serialize an object. You can choose the XML Serializer and the DataContract Serializer;


public class XmlSerializer
{
   public static MemoryStream SerializeToMemoryStream<T>(T t)
   {
      var memorystream = new MemoryStream();
      var s = new System.Xml.Serialization.XmlSerializer(typeof (T));

      xmlserializer.Serialize(XmlWriter.Create(memorystream), t);

      memorystream.Flush();
      memorystream.Seek(0, SeekOrigin.Begin);

      return memorystream;
   }

   public static string SerializeToString<T>(T t)
   {
      return SerializeToString(t, Encoding.UTF8);
   }

   public static string SerializeToString<T>(T t, Encoding encoding)
   {
      var settingsString = encoding.GetString(SerializeToMemoryStream(t).ToArray());
      return settingsString;
   }
}

        public class DatacontractSerializer
        {
            public static MemoryStream SerializeToMemoryStream<T>(T t)
            {
                var stream = new MemoryStream();
                var s = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
                s.WriteObject(XmlWriter.Create(stream), t);
                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                return stream;
            }

            public static string SerializeToString<T>(T t)
            {
                return SerializeToString(t, Encoding.UTF8);
            }

            public static string SerializeToString<T>(T t, Encoding encoding)
            {
                var settingsString = encoding.GetString(SerializeToMemoryStream(t).ToArray());
                return settingsString;
            }
        }
    }

zaterdag 26 januari 2013

Autofac and multiple implementations of an interface


How can we use Autofac to inject multiple implementations of an interface into a class, and how can we choose a specific implementation?

Let's say we have this interface for an object with which you can view files:

public interface IViewer
{
   void View(string filename);
}


And we have multiple implementations:

public class PdfViewerLarge : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}

public class PdfViewerSmall : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}


public class XlsViewerLarge : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}


public class XlsViewerSmall : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}

As you can see we have four Viewers. How can we use Autofac to inject these Viewers into a class?
First let's register the Viewers with Autofac, in an MVC3 website:

var builder = new ContainerBuilder();
builder.RegisterControllers(typeof (MvcApplication).Assembly);
builder.RegisterType<PdfViewerBig>().As<IViewer>();
builder.RegisterType<PdfViewerSmall>().As<IViewer>();
builder.RegisterType<XlsViewerSmall>().As<IViewer>();
var container = builder.Build();

Autofac will automatically put all viewers into an IEnumerable<IViewer>, which you can resolve like this:

var viewers = container.Resolve<IEnumerable<IViewer>>();

And we can easily use this in an MVC3 website like this:

public class HomeController : Controller
{
   private readonly IEnumerable<IViewer> _viewers;

   public HomeController(IEnumerable<IViewer> viewers)
   {
   _viewers = viewers;
   }

   public ActionResult Index()
   {
      foreach(var viewer in _viewers)
      {
         viewer.View("filename.pdf");
      }

      return View();
   }
}


How to choose a specific implementation from a collection?

The example above of the HomeController is pretty stupid, as we're using each viewer to view a document, even if the viewer is not suited for the filetype. What we realy want is something like:

var viewer = _viewers.Single(it => it.Filetype == ".pdf");
viewer.View("file.pdf");

There are multiple ways to do this. These are the three I like:
1. Use an enum value with autofac
2. Use Metadata with Autofac
3. Use Metadata within each Viewer


Enum value with Autofac

If you can think of a way to describe every viewer with an enum then this is a good option. It works like this;

Declare an enum:

public enum ViewerType { PdfLarge, PdfSmall, XlsLarge, XlsSmall }

Next register the type using the enum with Autofac:


builder.RegisterType<PdfViewerLarge>()
   .Keyed<IViewer>(ViewerType.PdfLarge);


builder.RegisterType<PdfViewerSmall>()
   .Keyed<IViewer>(ViewerType.PdfSmall);


builder.RegisterType<XlsViewerLarge>()
   .Keyed<IViewer>(ViewerType.XlsLarge);


builder.RegisterType<XlsViewerSmall>()
   .Keyed<IViewer>(ViewerType.XlsSmall);

In an MVC Controller the Viewers will be injected like this:

public class HomeController : Controller
{
   private readonly IIndex<ViewerType, IViewer> _viewers;

   public HomeController(IIndex<ViewerType, IViewer> viewers)

   {
      _viewers = viewers;
   }
}


Now we can use this way to select the desired implementation in an ActionMethod :

public ActionResult Index()
{
   var viewer = _viewers[ViewerType.PdfLarge];

   // do something with viewer

   return View();
}


Metadata with Autofac

Autofac provides a way to add metadata to registered services:

builder.Register(c => new PdfViewerLarge())
   .As<IViewer>()
   .WithMetadata("FileType", ".pdf");

We can also use strong typed metadata. First we have to define which metadatakeys we have:

public interface IViewerMetadata
{
    string FileType { get; }
    long MaxFileSize { get; }
}

Now we can use this metadata to register a type:

builder.RegisterType<XlsViewerSmall>()
   .As<IViewer>()
   .WithMetadata<IViewerMetadata>(m =>
      {
         m.For(p => p.MaxFileSize, 10000);
         m.For(p => p.FileType, ".xls");
       });

In an MVC Controller the Viewers will be injected like this:

public class HomeController : Controller
{
   private IEnumerable<Meta<IViewer, IViewerMetadata>> _viewers;

   public HomeController(
             IEnumerable<Meta<IViewer, IViewerMetadata>> viewers)
   {
      _viewers = viewers;
   }
}

Now we can use this way to select the desired implementation in an ActionMethod :

public ActionResult Index()
{
   var viewer = _viewers.Single(
                   it => it.Metadata.FileType == ".xls" &&
                   it.Metadata.MaxFileSize > 1000
                               ).Value;


   // do something with viewer

   return View();
}



Metadata inside an implementation

Another option to store metadata is inside the implementation itself. This is the way it works:

First we take an implementation, for example the PdfViewerLarge.


public class PdfViewerLarge : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}


We have to add the metadata to it, as public properties. But first add the metadata to the interface:

public interface IViewer
{
   string FileType {get;}
   long MaxFileSize {get;}
   void View(string filename);
}

Next we can implement it:



public class PdfViewerLarge : IViewer
{

   public string FileType
   {
      get { return ".pdf"; }
   }
   
   public long MaxFileSize

   {
      get { return 1000000; }
   }



   public void View(string filename)
   {
      // Do something smart
   }
}

When we register the type in Autofac we don't have to include any metadata:


builder.RegisterType<XlsViewerSmall>()
   .As<IViewer>();

But we can still use metadata in our Actionmethod:


public ActionResult Index()
{

   var viewer = _viewers.Single(
                   it => it.Value.FileType == ".xls" &&
                   it.Value.MaxFileSize > 1000
                                ).Value;


   // do something with viewer

   return View();
}


One drawback of this method is that every type has to be instanciated first. If creating a new instance of a specific implementation is an expensive operation, the other two options are preferable.