Gigi
Gigi

Reputation: 29421

Is there an elegant pattern for Serialization?

I frequently find myself implementing this sort of class:

public class Something
{
    public string Serialize()
    {
        // serialization code goes here
    }

    public static Something Deserialize(string str)
    {
        // deserialization code goes here
    }
}

I would like to enforce this across all classes of this type by making the above class implement an interface that looks something like this:

public interface ISerializationItem<T>
{
    string Serialize();
    T Deserialize(string str);
}

Alas, this is not possible, because the the interface can't cover the static method, and the method needs to be static so that it does not depend on any instance of the class.

Update: Typically, I would deserialize as shown below; the static method effectively serves to construct an instance of the class, so I don't want to already have an instance at hand to be able to do this:

var str = "Whatever";
var something = Something.Deserialize(str);

Is there a proper way to enforce this constraint?

Upvotes: 6

Views: 2554

Answers (1)

kinstephen
kinstephen

Reputation: 811

Keep your "data" classes simple/pure of any logic and then write the serialization processes in a separate class. This will make maintaining the data classes and serializer easier. If each class needs customization then create attribute classes and decorate your data classes with these attributes.

Here is some pseudo example...

public class Employee
{
     public int Id { get; set;}

     [ForceSpecialHandling]
     public string Name { get; set; }
}

public class CustomSerializer
{
     public T Serialize<T>(string data)
     {
             // Write the serialization code here.
     }
}

// This can be whatever attribute name you want. 
// You can then check if the property or class has this attribute using reflection.
public class ForceSpecialHandlingAttribute : Attribute
{
}

Upvotes: 1

Related Questions