C# Selected Implementation of Interface - c#

Is there a way to select methods to be implemented in an interface? I think in Java they have adapter to only select what method you want.

There isn't a way to pick-and-choose what you implement. You can, however, from good to bad to worse...
good - break the interface up into multiple interfaces - your classes can pick and choose what interfaces they should inherit from based off of what functionality they should provide (your classes can inherit from as many interfaces as you want)
bad - throw a NotImplementedException
worse - silently do nothing
Do you have a need to do this or is it curiosity? It sounds like you're laying the foundation for a very confusing API if you're destroying the value of interfaces. They define contracts that callers rely on.

The point of an interface is to say "Hey, anything that implements me is guaranteed to have all of the members that I declare!"
If you want anything other than that, then you don't want an interface, or you want an interface that declares only method1, in your example.

Related

"Abstract" interface in C#

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.

Interfaces or classes when using objects

In my project I have defined an interface to describe the methods that each of my different database connection classes must have. This is called IDatabaseConnectivityObject. Each of my classes implements this interface to make sure that they all contain the same methods for running queries, making connections etc etc.
Consider the following code:
IDatabaseConnectivityObject adoDataBaseConnection = new DbProviderFactoryConnection();
DbProviderFactoryConnection adoDataBaseConnection = new DbProviderFactoryConnection();
Will the above lines both behave the same? If so why? If not then why not? What are the benefits of both?
It may be a really stupid question but I havent used interfaces all that long and I am not sure what line 1 does. It was my understanding that you couldnt make an instance of an interface as it merely defines behaviour so how is that line possible?
Will the above lines both behave the same? If so why?
At runtime yes. The difference is that if you declare the variable of type IDatabaseConnectivityObject then at compile time you will be able to see only the members of this interface on the variable. If on the other hand you declare it as DbProviderFactoryConnection then you will see all the members of this class.
As a good practice it is recommended to always work with the highest possible type in the hierarchy when declaring the variable (IDatabaseConnectivityObject in this case) which allows you to access all members that the consumer will need.
The first would allow you to swap in a different implementation of you IDatabaseConnectivityObject moving forward.
This is a good practice as it allows your system to be more resistant to change moving forward. Keeping the cost of change low is key.
Interfaces define the contract that consumers can rely on, the API if you will. The two lines are functionally the same if you intend to use members that are present on the interface.
Using the interface just expresses that you don't care how something is implemented, just that it is implemented to contract. Interfaces also promote Loose Coupling.
The benefit of programming against an interface is that you are programming against the "agreement" and not the "execution", or the contract and not the implementation. This has a large positive impact on testing as you can mock or stub interfaces during tests to reduce the number of extraneous dependencies in a test scenario.
A similar benefit to above is that using interfaces along with something like the factory pattern, IoC, or DI you can provide different implementations of the interface on the fly - for example, a different business logic handler for a different customer.
Another benefit is that it helps get around the lack of multiple inheritance. Most things can be expressed nicely via interfaces, and classes can implement multiple interfaces.
You've asked for benefits.
When you are programming against interfaces (and are using factories to create the concrete types) this makes unit-testing easier as you can mock the instance that is put into the logic (unit).
This is actually a 'Design Pattern Principle':
"Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)

When Should a Class Implement an Interface, and When Should it Not?

Should a class implement an interface always in order to enforce a sort of 'contract' on the class?
When shouldn't a class implement an interface?
Edit: Meaning, when is it worthwhile to have a class implement an interface? Why not have a class just have public members and private members with various accessor/setter functions?
(Note: Not talking about COM)
No, an interface is not always required - the public members of the class already form a contract.
An interface is useful when you want to be able to exchange one class for another when both offer similar functionality. Using an interface allows you to decouple the contract from the specific implementation. However this decoupling is not always necessary or useful.
Many classes in the .NET framework do not implement any interfaces.
Only use an interface when it is needed.
That is: when you want to have different implementations for a certain abstraction.
When, in the future, it seems that it would be better to have an interface for a specific class (because for instance, you want to have another implementation for the same concept), then you can always create the interface from your existing class. (ExtractInterface refactoring)
Interfaces become more necessary when you are doing unit testing, but it all depends on the context of your development. As Mark said, an interface IS the contract and implementing it forces you to adhere to the "rules" of that contract.
If you are trying to enforce the implementation of certain methods, then using an interface is perfect for that.
There are some nice examples here:
http://msdn.microsoft.com/en-us/library/ms173156.aspx
http://msdn.microsoft.com/en-us/library/87d83y5b(VS.80).aspx
An interface, here meaning the code construct and not the design abstraction, supports a basic principle of code design called "loose coupling". There are some more derived principles that tell you HOW code should be loosely coupled, but in the main, loose coupling helps allow changes to code to affect as small an area of the codebase as possible.
Consider, for example, a calculation of some arbitrary complexity. This calculation is used by 6 different classes, and so to avoid duplicating code, the calculation is encapsulated in its own class, Calculator. The 6 classes each contain a reference to a Calculator. Now, say that your customer comes to you and says that in one usage of Calculator, if certain conditions are met, a different calculation should be used instead. You might be tempted to simply put these two rules (usage rule and business rule) and the new calculation algorithm into the Calculator class, but if you do so, then two things will happen; first, you make Calculator aware of some implementation details (how it's used) outside of its scope, that it doesn't need to know and that can change again later. Second, the other 5 classes that use Calculator, which were working just fine as-is, will have to be recompiled since they reference the changed class, and will have to be tested to ensure you didn't break their functionality by changing the one for the 6th class.
The "proper" solution to this is an interface. By defining an interface ICalculator, that exposes the method(s) called by the other classes, you break the concrete dependence of the 6 classes on the specific class Calculator. Now, each of the 6 classes can have a reference to an ICalculator. On 5 of these classes, you provide the same Calculator class they've always had and work just fine with. On the 6th, you provide a special calculator that knows the additional rules. If you had done this from the beginning, you wouldn't have had to touch the other 5 classes to make the change to the 6th.
The basic point is, classes should not have to know the exact nature of other objects they depend on; they should instead only have to know what that object will do for them. By abstracting what the object DOES from what the object IS, multiple objects can do similar things, and the classes that require those things don't have to know the difference.
Loose coupling, along with "high cohesion" (objects should usually be specialists that know how to do a small, very highly-related set of tasks), is the foundation for most of the software design patterns you'll see as you progress into software development theory.
In contrast to a couple of answers, there are design methodologies (e.g. SOLID) that state that you should ALWAYS set up dependencies as abstractions, like an abstract base class or an interface, and NEVER have one class depend upon another concrete class. The logic here is that in commercial software development, the initial set of requirements for an application is very small, but it is a safe assumption, if not a guarantee, that the set of requirements will grow and change. When that happens, the software must grow. Creating even smaller applications according to strict design principles allows extending the software without causing the problems that are a natural consequence of bad design (large classes with lots of code, changes to one class affecting others in unpredictable ways, etc). However, the art of software development, and the time and money constraints of same, are such that you can (and have to) be smart and say "from what I know of the way this system will grow, this is an area that needs to be well-designed to allow adaptation, while this other section will almost surely never change". If those assumptions change, you can go back and refactor areas of code you designed very simply to be more robust before you extend that area. But, you have to be willing and able to go back and change the code after it's first implemented.
This once again comes down to what he means by "interface". There is some ambiguity between the term interface and Interface. When the term Interface is used it means an object that has no method declarations. When the term interface is used it means that you utilize a pre-defined set of functions (whether they be implemented or not) and override them with your logic if necessary. An example would be:
abstract class Animal
class Dog extends Animal
In this instance Animal == interface (or contract) for Dog
interface Measurable
class Cup implements Measurable
In this instance Measurable == Interface for Cup
A class should not implement interface/s unless you want to tell other parts of your program - "This class can do these things (but not specify how exactly it does what it does)".
When would you want to do that?
For example, say you have a game in which you have animals.. And say whenever an animal sees a human it makes it's sound (be it a bark, a roar etc.).
If all animals will implement interface IMakeSound in which there is a method called MakeSound, you will not have to care about what kind of animal it is that should make that sound.. All you'll have to do is to use the "IMakeSound" part of the animal, and call it's method.
I should add that when one reads in a class declaration that it implements a certain interface, it tells him a lot about that class, which is another benefit.
You may not always want an interface. Consider you can accomplish similar tasks with a delegate. In Java I used the Runnable Interface for multithreaded applications. Now that I program in .NET I rely a lot on delegates to accomplish my mulithreaded applications. This article helps explains the need for an Delegate vs an Interface.
When to Use Delegates Instead of Interfaces (C# Programming Guide)
Delegates provide a little more flexibility as in Java I found that any task that I accomplished in C with a function pointer now required incasulation with an an Interface.
Although, there are lots of circumstances for an Interface. Consider IEnumerable, it is designed to allow you to iterate over various collection without needing to understand how the underlying code works. Interfaces are great for when you need need to exchange one class for another but require a similar Interface. ICollection and IList provide a set of similar functionality to accomplish an operation on a collection without worrying about the specifics.
If you would like to better understand Interfaces I suggest you read "Head First Design Patterns".

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.

Benefits of implementing an interface

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.

Categories

Resources