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.
Related
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(){
...
}
}
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.
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".
In the project I'm working on, I've noticed that for every entity class there is an interface. It seems that the original motivation was to only expose interfaces to other project/solutions.
I find this completely useless, and I don't see the point in creating an interface for every class. By the way, those classes don't have any methods just properties and they don't implement the same interface.
Am I wrong? Or is it a good practice?
Thx
I tend to create an interface for almost every class mainly because of unit testing - if you use dependency injection and want to unit test a class that depends on the class in question, than the standard way is to mock an instance of the class in question (using one of the mocking frameworks, e.g. Rhino-Mocks). However, practically it is only possible only for interfaces, not concrete implementations (yes, theoretically you can mock a concrete class, but there are many painful limitations).
There may be more to the setup than described here that justifies the overhead of interfaces. Generally they're very useful for dependency injection and overall separation of concerns, unit testing and mocking, etc.. It's entirely possible that they're not being used for this purpose (or any other constructive purpose, really) in your environment, though.
Is this generated code, or were these manually created? If the former, I suspect the tool generating them is doing so to prepare for such a use if the developer were so inclined. If the latter, maybe the original designer had something in mind?
For my own "best practices" I almost always do interface-driven development. It's generally a good practice to separate out concerns from one another and use the interfaces as contracts between them.
Exposing interfaces publicly has value in creating a loosely-coupled, behaviour-driven architecture.
Creating an interface for every class - especially if the interface just exposes every public method the class has in a single interface - is a bad implementation of the concept, and (in my experience) leads to more complex code and no improvement in architecture.
It's useful for tests.
A method may take a parameter of type ISomething, and it can be either SqlSomething or XmlSomething, where ISomething is the interface, and SqlSomething and XmlSomething are classes that implement the interface, depending whether you're doing tests (you pass XmlSomething in this case) or running the application (SqlSomething).
Also, when building a universal project, that can work on any database, but aren't using an ORM tool like LINQ (maybe because the database engine might not support LINQ to SQL), you define interfaces, with methods that you use in the application. Later on, developers will implement the interfaces to work with the database, create MySQLProductRepository class, PostgreSQLProductRepository class, that both inherit the same interface, but have different functionality.
In the application code any method takes a parameter a repository object of type IProductRepository, which can be anything.
IMHO it sounds that writing interfaces for no reason is pointless. You cant be totally closed minded but in general doing things that are not immediatly useful tend to accumulate as waste.
The agile concept of Its either adding value or taking value comes to mind.
What happens when you remove them? If nothing then ... what are they there for?
As a side note. Interfaces are extremely useful for Rhino Mocks, dependency injection and so on ...
If those classes only have properties, then interfaces don't add much value, because there's no behavior that is being abstracted.
Interfaces can be useful for abstraction, so the implementation can be mocked in unit tests. But in a well-designed application the business/domain entities should have very little reasons to be mocked. Business/domain services on the other hand are a excellent candidate for interface abstraction.
I have created interfaces for my entities once, and it didn't add any value at all. It only made me realize my design was wrong.
It seems to be an interface is superior to an abstract base class primarily if/when it is necessary to have a class which implements the interface but inherits from some other base class. Multiple inheritance is not allowed, but multiple interface implementations are.
The main caveat I see with using interfaces rather than abstract classes (beyond the extra source code required) is that changing anything in an interface necessitates recompilation of any and all code which uses that interface. By contrast, adding public members to a base class generally only requires recompilation of the base class itself.(*)
(*) Due to the way extension methods are handled, adding members to a class won't "require" recompiling code which uses that class, but may cause code which uses extension methods on the class to change meaning the next time it (the extension-method-using code) is recompiled.
There is no way to tell the future and see if you're going to need to program against an interface down-the-road. But if you decide later to make everything use an interface and, say, a factory to create instances of unknown types (any type that implements the interface), then it is quicker to restrict everyone to programming against an interface and a factory up-front than to replace references to MyImpl with references to IMyInterface later, etc.
So when writing new software, it is a judgment call whether to program against an interface or an implementation, unless you are familiar with what is likely to happen to that kind of software based on previous experiences.
I usually keep it "in flux" for a time whether or not I have an interface, a base class, or both, and even whether the base class is abstract (it usually is). I will work on a project (usually a Visual Studio solution with about 3 to 10 projects in it) for a while (a couple of days, maybe) before I refactor and / or ask for a second opinion. Once a final decision is reached and the code is refactored and tested, I tell fellow devs that it is ready for use.
For unit testing, it's either interfaces everywhere or virtual methods everywhere.
Sometimes I miss Java :)
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.