The main goal is to help developers to keep their objects encapsulated and not show the state outside of their internal borders. It's been inspired by yegor256 and his ideas presented in this webinar. The package helps objects to provide an internal state as data. Once an object needs to be printed out as data it has to implement the interface described below.
public interface IPrintable
{
void PrintTo(IMedia media);
}
IMedia interface represents an output where the object will be printed out. It can be easily printed out into any data format but main idea is to let the objects to print themselves. The most interesting insight is to let UI pages implement IMedia interface and bind objects data directly on UI elements. Initially interface implementation may look like this:
public class Foo : IPrintable
{
private string _internalData1;
private string _internalData2;
public void PrintTo(IMedia media)
{
media
.Put("Data1", _internalData1)
.Put("Data2", _internalData2);
}
}
There are two printable formats supported out of the box:
- Json
- Dictionary
The most used data format is Json. Once an object implements IPrintable interface it can use ToJson extension method printing itself into json format.
var myFooJson = new Foo().ToJson(); // Foo class should implement IPrntable interface
Sometimes it's necessary to have an access to objects' data but located in memory. DictionaryMedia class was introduced to manage this needs.
var myFooDictionary = new Foo().ToDictionary(); // Foo class should implement IPrintable interface
public static class PrintableExtensions
{
public static JObject ToJObject(this IPrintable printable)
{
var dictionary = printable.ToDictionary();
var jObject = new JObject();
foreach (var obj in dictionary)
{
object value = obj.Value is IPrintable printableObj
? printableObj.ToJObject()
: obj.Value;
jObject.Add(new JProperty(obj.Key, value));
}
return jObject;
}
}