Luchspeter
Luchspeter

Reputation: 804

Deserializing interface objects

I tried the SOLID architecture within my last project.

I have an Interface called ILog and a class Logthat implemented ILog. (In my understanding that should be done to follow the Open/Closed principle)

In order to stay open for extensions I implemented the front end via List<ILog> instead of with the firm implementation List<Log>.

Serializing the List<ILog> is no problem, but deserializing is. I understand why of course, because the deserializer does not know which implementation class it should use.

Question: How to know into which concrete type to deserialize an object that was serialized through an interface reference?

Upvotes: 0

Views: 95

Answers (1)

Felix K.
Felix K.

Reputation: 15683

Serializing the List is no problem, but deserializing is.

If you are deserializing you necessarily need to somehow communicate to your serializer which conrete representation of your interface to use. In case of Json.NET you could use the JsonConstructorAttribute (see also this answer) or resolvers in combination with dependency injection.

Question: What does it help me to work with List if I have to define the specific implementation-class for data storage / data import anyways?

Interfaces decouple your code from the actual implementation, which results in various benefits. For example in terms of unit testing they make mocking easier (since you can satisfy the interface with a mocked instance instead of being forced to use the "real" class). Also Interfaces allow you to benefit from covariance/contravariance, which you wouldn't have with a classes in C#. For further reading on the benefits of interfaces, have a look at the various answers to this question or see this blog post.

The above being said, interfaces always introduce a certain level of overhead/abstraction and you need to evaluate per case/situation, whether they make sense or not.

What would be the best way to handle the data-storage of interface objects or are they only used at runtime?

You necessarily need to store concrete representations, which means at the time of persistance, you need to decide which concrete implementation to use for storage (and later deserialization).

Upvotes: 1

Related Questions