Interfaces - why are they used? [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How will I know when to create an interface?
Hi guys,
This will sound a bit thick, I guess, but I am battling to understand the reason to use interfaces. People keep saying that they are 'contracts' for classes. But, why use them? If I was a single developer, on an application, that I knew no one would ever work on (I know - not a common example, but I am just trying to understand), would I use Interfaces? They seem to just duplicate work. It seem I define what a class must implement, and then go an implement it. I'm doing it twice - why?
Please note: I am not in anyway saying they're useless... I'm just tying to find out why, in projects I work on, they define an IClass, and then based on that, define the class which they use...
Sorry if it's very basic... Just hoping someone can help me out.

I use interfaces because it makes my code a lot more modular. Using interfaces in combination with an inversion of control container (http://code.google.com/p/autofac/) will allow you to swap in various implementations of an interface easily.
Also, interfaces are easier to unit test.
Those are just a couple good reasons; really, there are more. But those are strong enough to make me want to use interfaces.

if you want to have several classes that all support the same set of methods. For example you might have a class that stores data and the code that calls them does not care about the details of which class its working with. They must implement methods store and fetch. In this case you can either have an interface with those 2 methods or you can have a common base class.
Why not have a comon base class.
you can only have 1 common base class and you need that for something else
they are really quite different that having a common base class feels forced

Related

C# 8 - multiple inheritance "abstract class"? [duplicate]

This question already has answers here:
Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?
(6 answers)
Closed 4 years ago.
It seems to me like the C# 8.0 feature, default interface member implementation, essentially allows one to create implementations at the interface level. Pairing that with the fact that a class can implement multiple interfaces, it seems eerily close to a multiple inheritance structure for classes. As far as I understand, this seems to be quite opposite to the core of the design of the language.
Where does this discrepancy stem from and what room does this leave for actual abstract classes to occupy?
This question has been suggested as an answer to mine and while it is useful, it doesn't exactly answer my question. To be more precise:
I always assumed that single inheritance is one of the core principles of C#'s design, which is why the decision to implement this feature is surprising to me, and I would be interested to know where it stems from (C#-specifically).
The linked question does not answer what room it leaves for abstract classes.
I always assumed that single inheritance is one of the core principles of C#'s design
This is just not accurate. Single inheritance is a means to design goal, but not a goal in itself.
It's like saying the automatic transmission is a core design principle for car makers, when the actual goal is making the car easier and safer. And looking the car market, manual transmissions still thrive in both the low end (because they're cheaper) and the high end (performance sports cars) of the market, where they are good fit for purpose. Many models in those areas can still be had with either type of transmission.
The actual design goal in C# leading to single inheritance is more about safety and correctness with regards to memory access and overload resolution. Multiple inheritance is difficult to verify mathematically for these things compared to single inheritance. But as they find elegant solutions, C# designers have added a number of features that stretch the bounds of single inheritance. Beyond interfaces, we have partial classes, generics (and later co/contravariance), and delegate members that all trend this direction.
In this case, the default implementation is effective in safely providing a weak multiple inheritance because the inherited functionality doesn't cascade down the inheritance tree from two directions. You can't create a conflict by inheriting two different classes with differing interface implementations; you are limited to either your own class implementation, the default implementation, or the single implementation available via inheritance.
Note that default interface implementation does not allow for multiple inheritance, at least not in the sense that was a problem for C++. The reason multiple inheritance is a problem in C++ is that when a class inherits from multiple classes that have methods with equal signatures, it can become ambiguous as to which implementation is desired. With default interface implementation, that ambiguity is impossible because the class itself does not implement the method. An object must be cast to the interface in order to call the implemented methods. So multiple methods with the same signature may be called on the same instance, but you must explicitly tell the compiler which method you are executing.
The linked post answers your first question to a good extent.
As for:
The linked question does not answer what room it leaves for abstract
classes.
While it may read and sound similar interface default method implementation certainly does not replace abstract classes nor does it make them redundant, the very big reason being:
an interface cannot define class level fields/variables whereas an abstract class can have state.
There are some other differences although not as big as the aforementioned, which you can find in various blogs/posts:
https://dotnetcoretutorials.com/2018/03/25/proposed-default-interface-methods-in-c-8/
https://www.infoq.com/articles/default-interface-methods-cs8
etc.

Why do we need extension method if inheritance is already there..? [duplicate]

This question already has answers here:
Extension methods versus inheritance
(9 answers)
Closed 6 years ago.
I am facing this question regularly in interview. But I am not getting it's answer anywhere.Please help me.
Inheritance and extension methods are entirely orthogonal. It's just a simple way of writing a function in C# using the familiar . syntax. They only look similar if you use inheritance for code reuse, which tends to be frowned upon (but make sure you understand why - "best" practices are context-sensitive :)).
In any case, I'd expect the question is there to get you talking. Don't focus too hard on what the "right" answer is - just outline what inheritance is used for according to you, and what extension methods are used for, and what benefits and drawbacks each of those has. Get the dialog running.
For me, for example, extension methods are all about making common functions against an interface. That is, the functions add functionality on top of an interface (or class) while only using its public interface. This makes the "size" of the interface available to the function much smaller, which in turn makes it much easier to reason about.
Different people use extension methods differently, just like different people use inheritance differently. However, I find that as you shift from inheritance to composition, extension methods become more and more useful (and really, natural). Inheritance is a very specific technique that started being used for pretty much everything with little reason, but that's a big topic on Programmers.SE already anyway, just like the composition vs. inheritance debate :))

How Can I Learn when to build my own Interfaces [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Interfaces: Why can’t I seem to grasp them?
How will I know when to create an interface?
I am using C# and I know what are the interfaces and how syntatically use them,etc.
but what I have not learned yet is that when I am tasked to write a project, create a component,... How should I learn better about interfaces so when I want to do something I be able to Think about using them in my design...or for example I want to learn about dependency injection or even using mocking objects for testing, these are all related to good understanding of interfaces and know when and how to use them ... Can you plase provide me some good advice, reading,... then can help me with that?
Use interfaces when you have several things that can perform a common set of actions. How they do those actions can be different, but when as far as using the classes they act the same.
A good real world example is like a network drive vs a regular hard drive. Either way you can perform basic file operations. How they're actually done is different, but most of the time when you want to do something on a drive you don't care if it's a network drive or a physical one. That's an interface.
In hardware, different keyboards are designed differently, they (could) have buttons in different locations, but none of that matters to the computer. The computer's view of a keyboard's interface is the same regardless of any aspects other than it sends key strokes.
What is the interface these things must have in common if they are going to be used in the same way?
If you can answer that then you are on your way to design and using the interface properly in real life scenarios.
The goal of interfaces is to reduce coupling between components of your application. By using interface, you are binding to a contract instead of an implementation. This means that you can change the implementation as you see fit, provided you follow the same contract.
For example, it is considered good practice to use IList<T> instead of List<T>, because IList<T> only states that you need something that acts like a list. This way, other implementations of lists can be substituted without affecting your code. (For example, NHibernate, an object mapping and data access library, uses this to allow lazy loading of collections.)
Excellent candidates for interfaces are classes that interact with external systems (File system, database, network, web services, etc...). If you directly use those systems in your code, you will have trouble testing and refactoring.
I personally find interfaces especially useful in dependency injection and testing scenarios. Since you already understand what interfaces are, you should be able to understand dependency injection. Reading on those concepts will help you recognize good candidates for interfaces.
It's really something that you learn to use with experience.
I've found understanding how interfaces are used in plugin architectures really helpful.
Lots of links out there, e.g. : http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx
Try to imagine how you might write that sort of architecture without using interfaces - then you might fully appreciate what they bring to the table.
If using a a TDD-like workflow, interfaces are often used to define the requirements an object has of another object that it will eventually use. Using interfaces in this fashion allows them to be used to create 'seams' in your application where logic can be replaced/inserted/etc.
One way of thinking about interfaces in this fashion is to think of your objects as sending messages to one another, and that the interfaces are the definitions of the messages that can be sent.

About interfaces [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Interfaces: Why cant I seem to grasp them?
What is the purpose of interfaces in C#?
How would they enable extendable,modular design in c#,Java?
As far as my experience with the interfaces is concerned ,we used in a gridview scenario where columns values are brought from disparate objects.
(e.g:
List<IPub> list = new List<IPub>();
gridview.DataSource = list;
gridview.DataBind();
IPub has 4 methods which is implemented by 4 or 5 disparate classes.
)
What are the cases they come in handy compared to their class counterparts,apart from above?
I heard Java creator despised of interfaces or saying like "If i were a given a chance to design java again;I would never make interfaces into the language".
Does this applies to C# as well?
What implications made him to say that ?
I am feeling like i never understood interfaces completely.
Please somebody take pains to explain.
EDIT: Here is the Goslings quote, see the Java section
Interfaces can be considered as "can-do", whilst abstract/base classes can be considered as "is-a".
So a dog is-a animal, so you'd used a base class.
A dog can-do a poo, so poo would be a method on an interface which other animals might implement.. (crap example)
Reading my OO book the other day it posited that concrete instances should be avoided and good OO coders always program to an interface or base-class.
With that in mind it might be worth picking up a copy of a good OO / patterns book, such as head first design patterns
you should see the answers here or here or here or here
An interface provides a way to use something without having to worry about how that thing is implemented.
If you have an interface ITextGetter with a method GetText(string textKey) which you are using, you don't know if where the text comes from, all you know is that when you ask for the text with a particular key, you get the text. If you write you app using this interface then you can use different classes which all implement the interface to get the text without having to change your app. This makes it easy to switch from file based text getting to database based or webservice based text getting without having to change any of the code that uses the interface
Interfaces are a sort of contract: if some class implements some interface, then that class guarantees to have certain methods. You could have the same when you inherit from some baseclass, but you can't always do that. In that case an interface is handy to implement a sort of multiple inheritance.
Interfaces are there so that you don't need to specify a whole lot of functional code about something. You just need to know what it does. It's kinda like if you need to hire a family car.
You need to know
A) its a car that drives and
B) it has a family sized boot.
You don't need to know about how the car works, how the engine works. You just need to do know it can do A) and B). That's the purpose of an interface.
Within C# we don't allow multiple inheritance, (i.e. having more than 1 base class), so if you want to define the behaviour of more than 1 interface you can't do it with classes. If multiple inheritance existed there would be the option of using multiple base classes to do this.
Well, back when java was being developed there was a thing called "Multiple inheritance" where classes could be derived from two (or more) different classes.
So for example, you had a "Vehicle" class and a "Animal" class you could have a "Horse" class that derived from both.
The problem was, what if you wanted to derive a class from two classes that had a function name in common? You couldn't really, there would be two underlying implementations of the function.
So for example the Vehicle and Animal classes might have a "move()" function. Well, if you don't override that yourself, then what happens when you call horse.move()? It's undefined! Either one could get called!
So, in Java, you can only derive from one class. But what if you really need a class that is compatible with more then one type? Like if you have, for example a database connection that needs to derive a base class to work with the DB but also needs to be able to be managed like a resource with a close() function.
Okay, so they created 'Interfaces'. When you implement an interface, you don't have to worry about competing code underneath because you have to implement them yourself.
It's generally agreed that multiple inheritance is a "considered harmful" (like GOTO), and interfaces are a way of getting the benefits without the downsides. But, nowadays there are other ways to do that. Such as "DuckTyping" where as long as classes implement the feature name, they are good to go.
Also, java now can do nested classes, so if you need your class to be derived from two classes, you can make an inner class that derives from the second class.
Different methods have their pluses and minuses, but interfaces are not the only want to get around the problems of multiple inheritance today.
Interfaces give you a way to effectively have some sort of multiple inheritance (you can't inherit from more than one abstract base class). If you ask yourself the question why would you prohibit multiple class inheritance, just read relevant chapter from one of Bjarne Stroustroup's books (on C++), where you will how overcomplicated it gets.
On the other note, when you are using unit testing, pretty much every interface you create will have at least 2 implementations - the real one and a mocked one for the tests.

fields not allowed in C# interface

There are quite a lot of deviations in Java and C# languages, one of which I observed was we cannot add variable constants in an interface. Being from Java background I got baffled to see compilation error when I tried this.
Does anyone has explanation why it is so?
A field is an implementation detail of a class and should not be exposed an its interface.
An interface is a way to abstract away implementation details of a class. These two concepts look contradictory and don't really fit together.
You can declare properties in interfaces instead.
UPDATE (after realizing the question was about constants, not variable fields): I think (purely my personal speculation) that Java decided to allow such a construct because it didn't have enum types back then. C# has had enums since the beginning and preferred those to constants most of the time. Moreover, you can create a static class in C# and add everything you like in it and ship it along the interface without any real hassles. Supporting such a construct would just make interface definitions more complicated.
I've rarely wanted to have an actual constant in an interface - they usually make more sense in classes. The practice of using a Java interface to just contain constants (in order to reduce typing in classes that use them) is nasty; I'd only put constants in interfaces where they were related to functionality within the interface itself.
However, on occasion I've thought it would be nice to be able to define an enum within an interface, if that's the only context in which the enum is anticipated to be used. Interestingly, VB allows this even though C# doesn't.
Effectively both of these would be a way of turning the interface into a "mini-namespace" in its own right. However, I can't say I've missed it very often when writing C#. As the C# team is fond of saying, features aren't removed - they're added, and the cost of adding a feature is very high. That means the feature really needs to pull its weight - there has to be a significant benefit before the feature is added. I personally wouldn't put this very high up on the list.
Related thought: it might be nice to be able to define a nested class within the interface, usually an implementation of the interface - either to express its contracts or to act as a "default" implementation for situations where there is such a thing.
and adding constants to interfaces is discouraged in Java too (according to Effective Java at least)
Adding constants to an interface is wrong and should almost never be done. In the past many people declared Interfaces with many constants and then made another class implement this interface so they could make use of the constants without qualifying said constant. This is of course another anti pattern and was only done because people were lazy. If you really want a constant in an interface define a method that returns that constant.

Categories

Resources