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
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.
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.
Because the implementation can be partial. If all those method reside in the same interface you have 4 methods that you maybe dont need but you have to provide an implementation for them. On the other hand you could have one interface for each method but then you have 4 interfaces that you sometimes need to implement. That's a lot of methods and interfaces that can be avoided in this way.
Related
This is an Academic question.
There is arguably an X-Y problem behind it, which I may post separately later. But I am actually specifically interested in the Academic Question, here.
I often find that I have groups of interfaces which all have properties in common. And I want to define a base interface to commonise those, partly for lack of repetition and partly so that I can pass around an object and use the common methods without knowing the exact type.
Maybe I have IFooRepository, IBarRepository, etc., and I can declare IRepository<TEntity>.
Or I have an IHappyBot, ISadBot, IConfusedBot, all of which have IBot in common.
Notably no class would ever directly implement these base interfaces - you'd never have something that implemented just IBot.
If we were talking about a hierarchy of classes, rather than interfaces, then I would say "Ah ... the base thing is an abstract class".
Is there anything analogous that I can do with the interface to document the expectation that IBot isn't going to get directly implemented.
A aspect of it that I'm interested is doing something that you can later detect via reflection, so that when I test my DI setup, I can say "Ah, this interface isn't expected to be bindable, because it's "abstract".
I mainly care about C# myself, but if this feature specifically exists in other major languages it would interesting to hear about it.
A philosophical question in response perhaps - But why should a class not be able to implement IBot if it wants to?
What about an abstract class? I might want an abstract base Bot class to implement IBot as a way to check that the Bot base class ticks all the functionality expected of a base Bot.
An interface is about defining what something can / should do, it's a list of functionality. In my mind it doesn't make much sense to say "something can't claim it satisfies this list of functionality".
An abstract class makes sense because sometimes the abstract class needs its implementation holes filled (abstract methods etc). This isn't the case with an interface.
I wouldn't think so, the implementation details of Interfaces are deliberately hidden from their collaborators. To allow the implementation details of an interface to be specified by the interface contract would be mixing metaphors and doesn't seem to make sense.
If you really want to achieve this, you could introduce a marker Attribute class, say [AbstractInterface], but I think the uses of that would be very limited (and suspect).
Your motivating example, that a DI system needs to know whether an interface is implemented directly or via a super-interface seems unconvincing to me. The DI system can just look for implementations, I would think.
I have an interface called IStructuredReader that reads some structured data from a file and displays it in a form. It has a member called Sync() that, when implemented, scans the data for a user-specified data pattern.
Some implementations of IStructuredReader don't have sync capability. Those implementations throw NotImplementedException for the Sync() method. I would like to be able to check for this method being implemented, so that I can dim the button on the form if it is not.
I can think of a number of ways that this could be done, all of which seem clumsy and complicated:
Separate the Sync method into its own interface, inherit it for those implementations that support the capability, and attempt to cast the reader object to it to identify the capability,
Write a NotImplementedAttribute, decorate the member with it, and check for the presence of the attribute using Reflection,
Add a HasSyncCapability boolean property to the interface.
Is there a canonical way this is done?
This sounds like you really should have two interfaces. Your Sync() method is obviously adding functionality over your base interface, which suggests that this is really a separate concern, as it's not a requirement of IStructuredReader. I would suggest adding a second interface for the types which support this, which would then be easy to check for in your view layer.
The canonical way is for the interface to expose the methods that will be implemented, so the cleanest solution I see is to create another interface called maybe Syncronizable with just that method. If your object implements that interface you know the method is there, and this is not clumsy at all. Using reflection or the extra attribute are indeed not as clean as solutions, but it doesn't mean you shouldn't go for those if it makes your life easier ;)
I believe we invent things for some reasons: OOP came because procedural programming didn't meet our needs; The same goes for the Interface, because other OOP features like Abstract didn't meet our needs.
There are plenty of articles and guides written about what an Interface IS, CAN DO and HOW TO USE IT, however, I'm wondering what the actual philosophy behind the of creation of Interface is? Why we need to have Interface?
Conceptually, an interface is a contract. It's a way of saying that anything implementing this interface is capable of doing these set of things.
Different languages have different things that interfaces can define, and different ways of defining them, but that concept remains.
Using interfaces allows you to not care how some particular task is completed; it allows you to just ensure that it is completed.
By allowing implementations to differ, and allowing the code to define just the smallest subset of what it needs, it allows you to generalize your code.
Perhaps you want to write a method to write a sequence of numbers on the screen. You don't want to go around writing methods for doing that for an array, a set, a tree, on any of the (many) other commonly used data structures. You don't need to care whether you're dealing with an array or a linked list, you just need some way of getting a sequence of items. Interfaces allow you to define just the minimal set of what you need, lets say a getNextItem method, and then if all of those data structures implement that method and interface they can use the one generalized method. That's much easier than writing a separate method for each type of data structure you want to use. (This isn't the only use of interface, just a common one.)
In Java, classes can inherit just from one class, but they can implement multiple interfaces. Interfaces are similar to abstract classes, but if a class extends an abstract class then that class can't extend any other class. Interfaces solve that problem, you can make a class extend an abstract class and implement many interfaces.
I completely agree with susomena, but that's not the only benefit you get, when using interfaces.
For example. In our current application, mocking plays an important role, regarding unit testing. The philosophy of unit testing is, that you should really just test the code of this unit itself. Sometimes, though, there are other dependencies, the "unit under test" (SUT) needs to get. And maybe this dependency has other dependencies and so forth. So instead of complicatetly building and configuring the dependency tree, you just fake this certain dependency. A lot of mocking frameworks need to be setup with the interface of the class, which the SUT depends on. It is usually possible to mock concrete classes, but in our case mocking of concrete classes caused weird behaviours of unit tests, because of constructor calls. But mocking interfaces didn't, because an interface hasn't got a constructor.
My personal philosophy of choosing an abstract class implementation is building an hierarchical class construct, where some default behaviour of the abstract base class is needed. If there isn't any default behaviour, the derived class should inherit, I don't see any points of not choosing an interface over an abstract class implementation.
And here an other (not too good) example of how to choose one over another technique. Imagine you got a lot of animal classes like Cat and Dog. The abstract class Animal might implement this default method:
public abstract void Feed()
{
Console.WriteLine("Feeding with meat");
}
That's alright, if you got a lot of animals, which just are fine with meat. For the little amount of animals, which don't like meat you'd just need to reimplement a new behaviour of Feed().
But what if the animals are a kinda gourmets? And the requirement was, that every animal gets its preferred food? I'd rather choose an interface there, so the programmer is forced to implement a Feed() method for every single type of IAnimal.
IMO the best text that describes interface is the ISP from Robert Martin.
The real power of interfaces comes from the fact that (1) you can treat an object as if it has many different types (because a class can implement different interfaces) and (2) treat objects from different hierarchy trees as if they have the same type (because not related classes can implement the same interface).
If you have a method with a parameter of some interface type (eg., a Comparable), it means this methods can accept any object that implements that interface "ignoring" the class (eg., a String or a Integer, two unrelated classes that implement Comparable).
So, an interface is a much more powerful abstraction than abstract class.
Interfaces were brought into OOP because of the sole reason of it's use in the producer consumer paradigm. Let me explain this with an example...
Suppose there is a vendor that supplies tyres to all the big shot automobile companies. The automobile comapny is considered to be the CONSUMER and the tyre vendor is the PRODUCER. Now te consumer instructs the producer of the various specifications in which a tyre has to be produced(such as the diameter, the wheel base etc.); And the producer must strictly adhere to all of these specs.
Let's have an analogy to OOP from this... Let us develop an application to implement a stack, for which you are developing the UI; and let us assume that you are using a stack library (as a .dll or a .class) to actually implement the stack. Here, you are the consumer and the person who actually wrote the stack program is the producer. Now, you specify the various specifications of the stack saying that it should have a provision to push elements and to pop elements and also a provision to peep at the current stack pointer. And you also specify the interface to access these provisions by specifying the return types and the parameters (prototype of functions) so that you know how to use them in your application.
The simplest way to achive this is by creating an interface and asking the producer to implement this interface. So that, no matter what logic the producer uses(u are not bothered about the implementation as long as your needs are met one way or the other), he will implement a push,pop and a peep method with exact return types and parameters .
In other words, you make the producer strictly adhere to your specs and the way to access your needs by making him implement your interface. You won't accept a stack by just any vendor, if he doesn't implement your interface; Because you cannot be sure if it'll suit your exact need.
class CStack implements StackInterface
{//this class produced by the producer must have all three method implementation
//interface defined by the consumer as per his needs
bool push(int a){
...
}
int pop(){
....
}
int peep(){
...
}
}
I understand that an interface is an abstract type that contains no data, but exposes behaviours and properties, and that an instance of an object is an occurrence or a copy of an object that exists in memory.
I'm wondering about the differences in how the compiler / underlying code deals with the two? Based on the answer to this, why is the code more loosely coupled if I pass an interface as a dependency to an object rather than a concrete instance? What is the difference between what happens if I call the DoSomething method defined in an Interface to MyClass rather than the DoSomething method defined in the concrete instance of MyClass?
I know you said you understood what an interface is - but I do wonder if that's entirely true given the way that you've linked your second question with the first. The second can be answered without any knowledge of the first, nor is it influenced in any way by it.
Specifically on the question of why it's more loosely coupled has nothing to do with the implementation of the compiler or anything: it's just software architecture.
Interfaces impose no restrictions on the implementing type other than the presence of the method/property (well, technically they're methods too).
The implementation doesn't even have to be public on the type itself, nor does the type have to have a certain constructor etc. More importantly - it doesn't even have to be a class. Then there's the (rather edge-case) thing that with interfaces a single type can have multiple implementations of the same interface.
As soon as you use a base class potentially introduce a whole load of other restrictions.
True, these can clearly be a good thing too - for example if a known concrete base is known to be immutable (for consistency) and which doesn't allow 'nulls' in it's constructor etc (all not enforcable through an interface).
You can have many implementations (concrete instances) of an interface or abstract class.
In general you should define methods that accept the class hierarchy with the interface and not the concrete classes, so that they will be generic and wont have to be rewritten for each new implementation you define.
Calling the method on the base class or in the derived class should call the same method, assuming you correctly override the method.
Have a look at the MSDN magazine article: "Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects" for implementation details.
I think the main reason why the runtime needs to support interfaces is especially related to the fact that assemblies with different compile times might connect to each other at runtime.
what are the benefits of implementing an interface in C# 3.5 ?
You'll be able to pass your object to a method (or satisfy a type constraint) that expects the interface as an argument. C# does not support "duck typing." Just by writing the methods defined by the interface, the object will not automatically be "compatible" with the interface type:
public void PrintCollection<T>(IEnumerable<T> collection) {
foreach (var x in collection)
Console.WriteLine(x);
}
If List<T> did not implement the IEnumerable<T> interface, you wouldn't be able to pass it as an argument to PrintCollection method (even if it had a GetEnumerator method).
Basically, an interface declares a contract. Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.
The main benefit is about code readability, code maintainability and code "semantics".
Code readability: An interface constitutes a declaration about intentions. It defines a capability of your class, what your class is capable of doing. If you implement ISortable you're clearly stating that your class can be sorted, same for IRenderable or IConvertible.
Code semantics: By providing interfaces and implementing them you're actively separating concepts in a similar way HTML and CSS does. A class is a concrete implementation of an "object class" some way of representing the reality by modeling general properties of real life objects or concepts. An interface define a behavioral model, a definition of what an object can do. Separating those concepts keeps the semantics of your code more clear. That way some methods may need an instance of an animal class while other may accept whatever object you throw at them as long as it supports "walking".
Code maintainability: Interfaces helps to reduce coupling and therefore allow you to easily interchange implementations for the same concept without the underlying code being affected. You can change the implementation of a IMessage easily by defining a new class that implements the interface. Compare that to sistematically replacing all references from CMessage to CMyNewMessageClass.
It will help when you try to:
Unit test with Stubs / Mocks
Implement Dependency injection
Solve world hunger (although this unproven!)
Kindness,
Dan
Interfaces provide no actual advantage. Anything that can be done with an interface can, and should be done using other language constructions. Multiple inheritance is oft quoted as the only REAL benefit derived from using interfaces, but I can do multiple inheritance quite easily and clearly in C# - I do it every day. Changing the code without "breaking" the interface is the silliest of all excuses... That applies the same to concrete classes as it does to abstract classes or interfaces. As long as the functional signature does not change, you haven't broken the interface. Doesn't matter where it was declared. Simply putting a functional prototype in a separate file and naming it with an "I" in front buys nothing - except that you end up with twice as many source files to maintain. The supposition that the interface is defined early, and then maintains the contract is ridiculous. Interface methods and their parameters change ALL the time, because everything is never known up-front. That's why MicroSof stopped using them long ago. They had IUnKnown, IUnknown2, etc. It created a mess.
The main benefits of interfaces is mostly related to project design.
If you use an interface:
The consumer of the interface should implement that interface.
Designing bridge patters.
Creating a contract so that user must adhere the rules of the interface.
Can take only interface part (Object) from the main class.
Even class is private, can obtain the interface object from that
Multiple inheritance kind of style.
Need not be should implement, simple go for if implements that means if you want you can implement other wise can drop it..
Cleaner code.
Implementation which changes depends on class can go ahead with interface.
If each class have separate implementation of a method better to go for interfaces. For example IEnumerable in collections.
According to C# Architect, in a simple word it's a contract. Consumer must adhere to it.
An interface defines a contract (things that an object is able to do), while a concrete class (or struct) defines the concrete behavior.
For an example, IList is an interface, it defines the methods that a concrete object has to provide in order to be used like any other object implementing IList. Everywhere an IList can be used, your object that implements IList can be used as well. The way you concretely implement it and the way your object behaves when those IList methods are called is left to you.
If you work in a huge, commercial software house - you MIGHT want to consider the judicial use of Interfaces. Otherwise, you should stay away from them. Same for multi-threading. If I see one more script-kiddie app that spawns 20 threads to write "Hello World" I'm gonna freak. Multi-threading should be completely reserved for apps that require it, usually in a multi-processing environment. 90% of the time it causes more harm than good. And don't bother with the thread highjack / off-topic comments. I don't care. I've been doing this longer than most of you have been alive. Rank has its privileges.
You aren't tied to class inheritance - you can apply an interface to any class. Any class can have multiple interfaces - C# doesn't support multiple class inheritance, i.e. you are providing a good abstraction layer through the interface
An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
The way I understand it interfaces are most useful in these cases:
Cleaner division of labor among programmers. Lead programmer writes interface and junior programmer writes its implementation. That makes perfect sense to me. Lead programmer could write pseudocode instead of interface though.
Some specific situation, where you need 2 or more different implementations of the same class, for example interface animal and classes tiger and lion that use it. And even here it doesn't makes much sense, because lions and tigers share some things in common. Abstract class would be better, because if you use interface you have to write common functions in separate classes which leads to code duplication, which is bad.
You write a library and want it to be modifiable by users. So you write interface and its class implementation. User of your lib still has the possibility to write his own implementation class, which may use different technology/algorithm which achieves the same result, but maybe in a faster way for example. This is also the reason why we meet so many interfaces in libs we use, but rarely feel the need to write our own interfaces. Because we don't write libraries.