I have several POCO´s (simple classes holding data) that I have need to flush from memory from time to time whenever a collection grows too large. Most often I want to upload the data to a REST service, but if it fails I want to save the data to disk.
In the best of worlds, the code should be able to handle any data type. The problem I'm facing is who should be responsible for the conversion between object -> string | xml | json | ...
.
I could let all Pocos implement an interface (say ConvertToJson()
). But that would mean all classes that needs to be written has to have that interface and method which seems tedious, instead I would be happy with the default conversion instead of a class-specific.
writer.Write(poco.ConvertToJson());
Simplified code of what I have right now. It lacks support for different conversions (XML, Json).
public interface IWriter
{
bool Write(string data);
bool Write(Object data);
}
Writers (File and REST)
public static class FileWriter : IWriter
{
public bool Write(string data)
{
File.WriteAllText("file.txt", data);
}
public bool Write(object data)
{
XmlSerializer xs = new XmlSerializer(data.GetType());
using (TextWriter tw = new StreamWriter("file.txt")) { xs.Serialize(tw, data); }
}
}
public static class RestApiCaller : IWriter
{
public bool Write(string data)
{
MyHttpClient.CallRestService(data);
}
public bool Write(object data)
{
XmlSerializer xs = new XmlSerializer(data.GetType());
MyHttpClient.CallRestService(xs.Serialize(data));
}
}
Example of calling code
static void Main(string[] args)
{
// Write DeathStar as XML to rest service. This was easy!
List<DeathStar> deathStars = new List<DeathStar>(...);
if(!RestApiCaller.Write(deathStars))
{
// I dont know how to write my deathStar as JSON
FileWriter.Write(deathStars);
}
}
Who should do the conversion?
- The Poco classes?
- The Writer?
- a dedicated converter?
- if so, who calls the converter, the poco, Writer, or the calling code?
And should a writer only accept string
as input? Both XML and Json are strings in the end, but I'm not sure if that is desirable. I would like the answer to be following SOLID.