Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnSerializing/OnSerialized/OnDeserializing/OnDeserialized why not an interface?

I've been doing some reading on serialization in .NET and started wondering what was the main reason of implementing the OnSerializing/OnSerialized/OnDeserializing/OnDeserialized functionality as attributes in contrast to an interface. I can think of some pros and cons but I'm probably missing something crucial so I wanted to know what outweighed.

In favor of an interface:

  • Method signatures are checked at compile time (using an attribute on a method with an incorrect signature causes a runtime exception)

  • No two methods could be declared for a single event on a class level (decorating two methods with the same attribute causes a runtime exception)

In favor of attributes:

  • No need to declare 4 methods if we want to react to a single event
like image 830
grysik44 Avatar asked Dec 13 '22 15:12

grysik44


2 Answers

An interface would not be as good because there is then no automatic way for each class in a hierarchy on top of the interface to provide its own implementation unless:

  • The base class declares the methods as virtual
  • Each deriving class re-implements the interface

Then there is the added complication of identifying each class's implementation - the reflection is harder.

Furthermore, once the interface is brought in, the implication is that all classes in a hierarchy are serializable, but this is not always, nor should it always, be the case. It is entirely proper to derive a non serializable class from a serializable base (in controlled circumstances) - but this is effectively prevented through the use of either interfaces or virtual methods.

The use of attributes, then, provide the tersest, most expressive and actually most flexible way to implement serialization.

like image 195
Andras Zoltan Avatar answered May 14 '23 02:05

Andras Zoltan


Here's another reason in favor of attributed methods over an interface.

If an interface were used, it would be possible for a subclass to override the method implementation, hiding the base class's implementation. Of course, the subclass's implementation would have a responsibility to explicitly invoke the overridden method, but it's usually a bad idea to make proper program behavior contingent upon programmer responsibility.

The way things are implemented now, a subclass's serialization triggered method will not hide the base class's. The serialization framework is responsible for making sure they all get called in proper order, and the serialization framework is trustworthy.

like image 26
Kennet Belenky Avatar answered May 14 '23 01:05

Kennet Belenky