Thursday, June 11, 2015

Serialization and encapsulation are not friends.

namespace ReverseEngineering.Core
{
   public class Cat
   {
      public int? NumberOfLegs { get; private set; }
      public int? NumberOfEyes { get; private set; }
      public int? NumberOfTails { get; private set; }
      
      public Cat(int? magicNumber=null)
      {
         if(magicNumber!=null) Magic(magicNumber);
      }
      
      private void Magic(int? magicNumber)
      {
         NumberOfLegs = magicNumber*4;
         NumberOfEyes = magicNumber*2;
         NumberOfTails = magicNumber*1;
      }
   }
}

 
 

When I try to serialize the above with this approach. I get...

  • InvalidOperationException was unhandled by user code
    • An exception of type 'System.InvalidOperationException' occurred in System.Xml.dll but was not handled in user code
    • Additional information: ReverseEngineering.Core.Cat cannot be serialized because it does not have a parameterless constructor.

 
 

When I hack around this problem by just adding a harmless parameterless constructor (which adds no new functionality to the class) I get this...

  • InvalidOperationException was unhandled by user code
    • An exception of type 'System.InvalidOperationException' occurred in System.Xml.dll but was not handled in user code
    • Additional information: Cannot deserialize type 'ReverseEngineering.Core.Cat' because it contains property 'NumberOfLegs' which has no public setter.

 
 

It's too bad my encapsulation can't be serialized because look at how awesome my encapsulation is! :P

No comments:

Post a Comment