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

I read about serialization in .NET and started wondering what was the main reason for implementing OnSerializing / OnSerialized / OnDeserializing / OnDeserialized functionality as attributes, as opposed to an interface. I can think of some pros and cons, but I probably missed something important, so I wanted to know what outweighs.

In favor of the interface:

  • Method signatures are checked at compile time (using a method attribute with the wrong signature raises an exception at run time)

  • No two methods can be declared for a single event at the class level (decorating two methods with the same attribute raises an exception at run time)

In favor of attributes:

  • No need to declare 4 methods if we want to respond to a single event
+4
source share
3 answers

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

  • Base class declares methods as virtual
  • Each producing class reimplement the interface

Then an additional complication of identification of each class implementation is added - reflection is more complicated.

In addition, after entering the interface, it is assumed that all classes in the hierarchy are serializable, but this does not always and should not always be so. It is quite correct to derive a non-serializable class from a serializable base (under controlled conditions), but this is effectively prevented using the interface or virtual methods.

Thus, the use of attributes provides the most expressive and most flexible way to implement serialization.

+8
source

Here's another reason to favor assignable methods on an interface.

If an interface was used, the subclass could override the implementation of the method, hiding the implementation of the base class. Of course, the implementation of the subclass will be responsible for explicitly invoking the overridden method, but this is usually a bad idea for the correct behavior of the program, depending on the responsibility of the programmer.

How everything is implemented now, the method of initiating serialization of a subclass will not hide the base class. The serialization structure is responsible for ensuring that they are all called in the correct order, and the serialization structure is trustworthy.

+4
source

Because the implementation may be partial. If all of these methods are in the same interface, you have 4 methods that you may not need, but you must provide them with an implementation. On the other hand, you can have one interface for each method, but then you have 4 interfaces that you sometimes need to implement. These are many methods and interfaces that can be avoided this way.

+1
source

Source: https://habr.com/ru/post/1343830/


All Articles