views:

190

answers:

2

Lets say I have some domain objects that will need to be serialized/packed using a custom binary format so they can be sent over sockets to external processes. My first instinct would be to create an interface that represents any object that can be packed into this binary format.

public interface IPackable
{
    byte[] Pack();
}

Then my domain objects (such as Entity, State, Vector, etc) would each implement this interface. This is similar to how the default serialization works in .NET and Java.

public class Vector : IPackable
{
  public double X { get; set; }
  public double Y { get; set; }
  public double Z { get; set; }

  // other operators and methods...

  public byte[] Pack
  {
    MemoryStream stream = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(stream);

    writer.Write(X);
    writer.Write(Y);
    writer.Write(Z);

    return stream.ToArray();
}

However, the more I learn about design principles (such as the SOLID's Single Responsibility Principle), the more I think that I should create a separate class for packing my domain objects.

I can see advantages and disadvantages with both. What do you all think? If the answer is create a separate class for packing the domain objects, should I create a separate packer for each domain object (such as EntityPacker, StatePacker, VectorPacker, etc)?

Thanks

+1  A: 

Have you also considered the System.Runtime.Serialization namespace?

The trouble with creating an external serializer is that you have to open all your interesting data to another object. Since most of your object's state is likely to be held in private variables, the exposed properties of an object don't necessarily provide enough information to fully describe it externally.

In sticking with good data encapsulation, I would favor hiding the details of packing / serializing in the object being stored.

jheddings
I thought that the default .NET serializer only serializes public properties/fields any. So, would this be any different?
dewald
Sorry, I missed your comment from before... You can fully control an object's serialization using the ISerializable interface.
jheddings
+1  A: 

There are several forms of serialization built into the .NET framework you can use for this purpose. Examples are SOAP, XML but also binary which lends itself well to sending objects over streams of all kinds, including network streams.

Binary serialization in .NET is also capable of serializing and deserializing private properties and fields whereas the build in XML and SOAP formatters are not.

However, you must be sure that when using the binary formatter that it is only compatible with .NET library whereas SOAP could be read from any SOAP capable platform.

Jaapjan