Related
Assuming I have an interface and 3 or 4 classes that implement the interface. Now let's say I have another method but it is relevant only for one or two implementing classes.
So as I see it there are two approaches
Declare the method in the interface, implement in all the classes. In classes that the method is not relevant - throw "not supported" exception.
Declare the method only in the implementing classes where relevant but then you have to downcast the instance from interface type to the specific type in order to call the method.
So would be your design here and why?
You should apply the interface segregation principle here, part of the SOLID principles. Instead of having one large interface, split the interfaces up into a few smaller interfaces. Implement the interfaces only in the classes that need it.
I would choose a parent interface. Make the classes that satisfy the interface implement that interface. Create a second interface that extends the first one and adds the extra methods and then make the remaining classes implement that interface. You would still be coding to an interface rather than an implementation and all your design principles are satisfied.
Ask yourself this, will the object that consume the interface necessarily expect this function to be there? Is it important that no matter which instance of the interface you pass, you'll still have that method available?
If the answer to that question is yes, 1. If no, 2.
I have some questions about the affects of using concrete classes and interfaces.
Say some chunk of code (call it chunkCode) uses concrete class A. Would I have to re-compile chunkCode if:
I add some new public methods to A? If so, isn't that a bit stange? After all I still provide the interface chunkCode relies on. (Or do I have to re-compile because chunkCode may never know otherwise that this is true and I haven't omitted some API)
I add some new private methods to A?
I add a new public field to A?
I add a new private field to A?
Factory Design Pattern:
The main code doesn't care what the concrete type of the object is. It relies only on the API. But what would you do if there are few methods which are relevant to only one concrete type? This type implements the interface but adds some more public methods? Would you use some if (A is type1) statements (or the like) the main code?
Thanks for any clarification
1) Compiling is not an activity in OO. It is a detail of specific OO implementations. If you want an answer for a specific implementation (e.g. Java), then you need to clarify.
In general, some would say that adding to an interface is not considered a breaking change, wheras others say you cannot change an interface once it is published, and you have to create a new interface.
Edit: You specified C#, so check out this question regarding breaking changes in .Net. I don't want to do that answer a disservice, so I won't try to replicate it here.
2) People often hack their designs to do this, but it is a sign that you have a poor design.
Good alternatives:
Create a method in your interface that allows you to invoke the custom behavior, but not be required to know what that behavior is.
Create an additional interface (and a new factory) that supports the new methods. The new interface does not have to inherit the old interface, but it can if it makes sense (if an is-a relationship can be expressed between the interfaces).
If your language supports it, use the Abstract Factory pattern, and take advantage of Covariant Return Types in the concrete factory. If you need a specific derived type, accept a concrete factory instead of an abstract one.
Bad alternatives (anti-patterns):
Adding a method to the interface that does nothing in other derived classed.
Throwing an exception in a method that doesn't make sense for your derived class.
Adding query methods to the interface that tell the user if they can call a certain method.
Unless the method name is generic enough that the user wouldn't expect it to do anything (e.g. DoExtraProcessing), then adding a method that is no-op in most derived classes breaks the contract defined by that interface.
E.g.: Someone invoking bird.Fly() would expect it to actually do something. We know that chickens can't fly. So either a Chicken isn't a Bird, or Birds don't Fly.
Adding query methods is a poor work-around for this. E.g. Adding a boolean CanFly() method or property in your interface. So is throwing an exception. Neither of them get around the fact that the type simply isn't substitutable. Check out the Liskov Substitution Principle (LSP).
For your first question the answer is NO for all your points. If it would be that way then backward compatibility would not make any sense. You have to recompile chunkCode only if you brake the API, that is remove some functionality that chunkCode is using, changing calling conventions, modifying number of parameters, these sort of things == breaking changes.
For the second I usually, but only if I really have to, use dynamic_cast in those situations.
Note my answer is valid in the context of C++;I just saw the question is language agnostic(kind of tired at this hour; I'll remove the answer if it offenses anybody).
Question 1: Depends on what language you are talking about. Its always safer to recompile both languages though. Mostly because chuckCode does not know what actually exists inside A. Recompiling refreshes its memory. But it should work in Java without recompiling.
Question 2: No. The entire point of writing a Factory is to get rid of if(A is type1). These if statements are terrible from maintenance perspective.
Factory is designed to build objects of similar type. If you are having a situation where you are using this statement then that object is either not a similar type to rest of the classes. If you are sure it is of similar type and have similar interfaces. I would write an extra function in all the concrete base classes and implement it only on this one.
Ideally All these concrete classes should have a common abstract base class or a Interface to define what the API is. Nothing other than what is designed in this Interface should be expected to be called anywhere in the code unless you are writing functions that takes this specific class.
A friend of mine goes back and forth on what "interface" means in programming.
What is the best description of an "interface"?
To me, an interface is a blueprint of a class. Is this the best definition?
An interface is one of the more overloaded and confusing terms in development.
It is actually a concept of abstraction and encapsulation. For a given "box", it declares the "inputs" and "outputs" of that box. In the world of software, that usually means the operations that can be invoked on the box (along with arguments) and in some cases the return types of these operations.
What it does not do is define what the semantics of these operations are, although it is commonplace (and very good practice) to document them in proximity to the declaration (e.g., via comments), or to pick good naming conventions. Nevertheless, there are no guarantees that these intentions would be followed.
Here is an analogy: Take a look at your television when it is off. Its interface are the buttons it has, the various plugs, and the screen. Its semantics and behavior are that it takes inputs (e.g., cable programming) and has outputs (display on the screen, sound, etc.). However, when you look at a TV that is not plugged in, you are projecting your expected semantics into an interface. For all you know, the TV could just explode when you plug it in. However, based on its "interface" you can assume that it won't make any coffee since it doesn't have a water intake.
In object oriented programming, an interface generally defines the set of methods (or messages) that an instance of a class that has that interface could respond to.
What adds to the confusion is that in some languages, like Java, there is an actual interface with its language specific semantics. In Java, for example, it is a set of method declarations, with no implementation, but an interface also corresponds to a type and obeys various typing rules.
In other languages, like C++, you do not have interfaces. A class itself defines methods, but you could think of the interface of the class as the declarations of the non-private methods. Because of how C++ compiles, you get header files where you could have the "interface" of the class without actual implementation. You could also mimic Java interfaces with abstract classes with pure virtual functions, etc.
An interface is most certainly not a blueprint for a class. A blueprint, by one definition is a "detailed plan of action". An interface promises nothing about an action! The source of the confusion is that in most languages, if you have an interface type that defines a set of methods, the class that implements it "repeats" the same methods (but provides definition), so the interface looks like a skeleton or an outline of the class.
Consider the following situation:
You are in the middle of a large, empty room, when a zombie suddenly attacks you.
You have no weapon.
Luckily, a fellow living human is standing in the doorway of the room.
"Quick!" you shout at him. "Throw me something I can hit the zombie with!"
Now consider:
You didn't specify (nor do you care) exactly what your friend will choose to toss;
...But it doesn't matter, as long as:
It's something that can be tossed (He can't toss you the sofa)
It's something that you can grab hold of (Let's hope he didn't toss a shuriken)
It's something you can use to bash the zombie's brains out (That rules out pillows and such)
It doesn't matter whether you get a baseball bat or a hammer -
as long as it implements your three conditions, you're good.
To sum it up:
When you write an interface, you're basically saying: "I need something that..."
Interface is a contract you should comply to or given to, depending if you are implementer or a user.
I don't think "blueprint" is a good word to use. A blueprint tells you how to build something. An interface specifically avoids telling you how to build something.
An interface defines how you can interact with a class, i.e. what methods it supports.
In Programming, an interface defines what the behavior a an object will have, but it will not actually specify the behavior. It is a contract, that will guarantee, that a certain class can do something.
Consider this piece of C# code here:
using System;
public interface IGenerate
{
int Generate();
}
// Dependencies
public class KnownNumber : IGenerate
{
public int Generate()
{
return 5;
}
}
public class SecretNumber : IGenerate
{
public int Generate()
{
return new Random().Next(0, 10);
}
}
// What you care about
class Game
{
public Game(IGenerate generator)
{
Console.WriteLine(generator.Generate())
}
}
new Game(new SecretNumber());
new Game(new KnownNumber());
The Game class requires a secret number. For the sake of testing it, you would like to inject what will be used as a secret number (this principle is called Inversion of Control).
The game class wants to be "open minded" about what will actually create the random number, therefore it will ask in its constructor for "anything, that has a Generate method".
First, the interface specifies, what operations an object will provide. It just contains what it looks like, but no actual implementation is given. This is just the signature of the method. Conventionally, in C# interfaces are prefixed with an I.
The classes now implement the IGenerate Interface. This means that the compiler will make sure, that they both have a method, that returns an int and is called Generate.
The game now is being called two different object, each of which implementant the correct interface. Other classes would produce an error upon building the code.
Here I noticed the blueprint analogy you used:
A class is commonly seen as a blueprint for an object. An Interface specifies something that a class will need to do, so one could argue that it indeed is just a blueprint for a class, but since a class does not necessarily need an interface, I would argue that this metaphor is breaking. Think of an interface as a contract. The class that "signs it" will be legally required (enforced by the compiler police), to comply to the terms and conditions in the contract. This means that it will have to do, what is specified in the interface.
This is all due to the statically typed nature of some OO languages, as it is the case with Java or C#. In Python on the other hand, another mechanism is used:
import random
# Dependencies
class KnownNumber(object):
def generate(self):
return 5
class SecretNumber(object):
def generate(self):
return random.randint(0,10)
# What you care about
class SecretGame(object):
def __init__(self, number_generator):
number = number_generator.generate()
print number
Here, none of the classes implement an interface. Python does not care about that, because the SecretGame class will just try to call whatever object is passed in. If the object HAS a generate() method, everything is fine. If it doesn't: KAPUTT!
This mistake will not be seen at compile time, but at runtime, so possibly when your program is already deployed and running. C# would notify you way before you came close to that.
The reason this mechanism is used, naively stated, because in OO languages naturally functions aren't first class citizens. As you can see, KnownNumber and SecretNumber contain JUST the functions to generate a number. One does not really need the classes at all. In Python, therefore, one could just throw them away and pick the functions on their own:
# OO Approach
SecretGame(SecretNumber())
SecretGame(KnownNumber())
# Functional Approach
# Dependencies
class SecretGame(object):
def __init__(self, generate):
number = generate()
print number
SecretGame(lambda: random.randint(0,10))
SecretGame(lambda: 5)
A lambda is just a function, that was declared "in line, as you go".
A delegate is just the same in C#:
class Game
{
public Game(Func<int> generate)
{
Console.WriteLine(generate())
}
}
new Game(() => 5);
new Game(() => new Random().Next(0, 10));
Side note: The latter examples were not possible like this up to Java 7. There, Interfaces were your only way of specifying this behavior. However, Java 8 introduced lambda expressions so the C# example can be converted to Java very easily (Func<int> becomes java.util.function.IntSupplier and => becomes ->).
To me an interface is a blueprint of a class, is this the best definition?
No. A blueprint typically includes the internals. But a interface is purely about what is visible on the outside of a class ... or more accurately, a family of classes that implement the interface.
The interface consists of the signatures of methods and values of constants, and also a (typically informal) "behavioral contract" between classes that implement the interface and others that use it.
Technically, I would describe an interface as a set of ways (methods, properties, accessors... the vocabulary depends on the language you are using) to interact with an object. If an object supports/implements an interface, then you can use all of the ways specified in the interface to interact with this object.
Semantically, an interface could also contain conventions about what you may or may not do (e.g., the order in which you may call the methods) and about what, in return, you may assume about the state of the object given how you interacted so far.
Personally I see an interface like a template. If a interface contains the definition for the methods foo() and bar(), then you know every class which uses this interface has the methods foo() and bar().
Let us consider a Man(User or an Object) wants some work to be done. He will contact a middle man(Interface) who will be having a contract with the companies(real world objects created using implemented classes). Few types of works will be defined by him which companies will implement and give him results.
Each and every company will implement the work in its own way but the result will be same. Like this User will get its work done using an single interface.
I think Interface will act as visible part of the systems with few commands which will be defined internally by the implementing inner sub systems.
An interface separates out operations on a class from the implementation within. Thus, some implementations may provide for many interfaces.
People would usually describe it as a "contract" for what must be available in the methods of the class.
It is absolutely not a blueprint, since that would also determine implementation. A full class definition could be said to be a blueprint.
An interface defines what a class that inherits from it must implement. In this way, multiple classes can inherit from an interface, and because of that inherticance, you can
be sure that all members of the interface are implemented in the derived class (even if its just to throw an exception)
Abstract away the class itself from the caller (cast an instance of a class to the interface, and interact with it without needing to know what the actual derived class IS)
for more info, see this http://msdn.microsoft.com/en-us/library/ms173156.aspx
In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.
In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).
As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.
As above, synonyms of "contract" and "protocol" are appropriate.
The interface comprises the methods and properties you can expect to be exposed by a class.
So if a class Cheetos Bag implements the Chip Bag interface, you should expect a Cheetos Bag to behave exactly like any other Chip Bag. (That is, expose the .attemptToOpenWithoutSpillingEverywhere() method, etc.)
A boundary across which two systems communicate.
Interfaces are how some OO languages achieve ad hoc polymorphism. Ad hoc polymorphism is simply functions with the same names operating on different types.
Conventional Definition - An interface is a contract that specifies the methods which needs to be implemented by the class implementing it.
The Definition of Interface has changed over time. Do you think Interface just have method declarations only ? What about static final variables and what about default definitions after Java 5.
Interfaces were introduced to Java because of the Diamond problem with multiple Inheritance and that's what they actually intend to do.
Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods , default definitions and static final variables.
http://www.quora.com/Why-does-Java-allow-static-final-variables-in-interfaces-when-they-are-only-intended-to-be-contracts
In short, The basic problem an interface is trying to solve is to separate how we use something from how it is implemented. But you should consider interface is not a contract. Read more here.
So my question is, why to use interfaces or abstract classes? Why are they useful, and for what?
Where can i use them intelligently?
Interfaces allow you to express what a type does without worrying about how it is done. Implementation can be changed at will without impacting clients.
Abstract classes are like interfaces except they allow you to provide sensible default behavior for methods where it exists.
Use and examples depend on the language. If you know Java, you can find examples of both interfaces and abstract classes throughout the API. The java.util collections have plenty of both.
They're useful when you want to specify a set of common methods and properties that all classes that implement/inherit from them have, exposed behaviors that all should provide.
Particularly about interfaces, a class can implement multiple interfaces, so this comes in handy when you're trying to model the fact that its instances must exhibit multiple types of behavior.
Also, as Wikipedia puts it, an interface is a type definition: anywhere an object can be passed as parameter in a function or method call, the type of the object to be exchanged can be defined in terms of an interface instead of a specific class, this allowing later to use the same function exchanging different object types: hence such code turns out to be more generic and reusable.
Whenever i hear about interfaces i have the following doubt.
i have the following interface
interface Imammals
{
walk();
eat();
run();
}
and i have two classes Human and Cat that implements this interface.
Anyway, the functionality of the methods are going to be different in both the Classes.
For Eg: walk(), the functionality differs as cat uses four legs and human uses two legs
Then, Why do i need to have a common interface which ONLY declares these methods? Is my design here faulty?
If the functionality of the methods are going to be same in both the classes, i could go for a class based inheritance where the parent implements the complete functionality and the child inherits and uses the parent class methods.
But here the interfaces help us just to consolidate the methods declarations or is there anything more inside?
EDIT: walking(), eating(), running() was changed to walk(), eat(), run() and mammals was changes to Imammals.
In your scenario, either type-inheritance or interface-implementation would work - but interface based abstraction allows types outside of your existing type model to provide the functionality. It could be a mock object, or it could be some kind of super killer robot, that can walk run and eat but isn't really a mammal (so having it inherit from a Mammal class could be confusing or just impossible).
In particular, interfaces allow us to express this relationship neatly, while avoiding the subtle points from C# having single (type-)inheritance.
Using the interface you can have the following:
public void walkMyAnimal(Animal animal) {
animal.walk();
}
without the need to know what animal exactly is passed.
Interface allows you to define behavior for inheriting classes so if you have Donkey in future then you simply implement this interface and be sure that you donkey will walk,run and eat.
Also you can use composition instead of concrete implementation if some of your objects have common behaviour.
Read a bit about Strategy pattern I think that will help.
One big advantage of interfaces is that even in languages like Java and C# where multiple inheritance is not allowed, a class can take on more than one interface. Something can be both Closable, for instance, and a List, but could not inherit from both (hypothetical) abstract base classes AbstractClosable and AbstractList.
It is also suitable for cases where you are writing a library or a plugin interface and want to provide a way for your code to use objects provided by library users or plugin writers, but you don't want (nor should you) any say in the implementation. Think of the Listener interfaces in Java, for instance. Without those, there would be no possibility of an event model, since Java doens't support callbacks.
In general, interfaces are good for cases where you want objects that have particular functionality, but the way that functionality is implemented can vary widely, and might not be the only thing a class does.
The reason you want an interface is to be able to treat them all alike when commanding them.
Whoever calls walking() (which is a rather odd name btw, it should probably be walk()) is just interested in telling your animal to do just that. The actual implementation will vary but that is not something the caller would care about.
Well, sometimes you'd want to be able to do something to "anything capable of running" without necessarily knowing at design time whether you're talking about a human or a cat or whatever. For instance, imagine a function mammal raceWinner(mammal m1, mammal m2){...}
to calculate which mammal would win in a race. To determine who wins, perhaps the function needs to call m1.running() and m2.running(). Of course, the mammals we pass in will really be cats or humans or whatever, and this class supplies the actual implementation of running(). But all raceWinner needs to know is that they have a running() method with the expected signature.
If we only defined running() on cat and human, we couldn't call m1.running() (because the compiler is not guaranteed that m1 has a running() method, as it only knows it's a m1 implements mammal). So instead we'd have to implement a raceWinner(human m1, cat m2) and likewise for two humans, two cats, or any other pair of mammals we had in mind, leading to a lot more work on our part.
An interface provides a contract. It doesn't provide an implementation. It's good practice to interface out your classes.
Of course, walking(), eating() will have different implementation in different animals. But they all walk, run, etc. That is all the interface is saying.
You could model this using inheritance, which would allow you to give default implementations for some or all of the methods. However, interfaces are really useful for declaring a set of features that apply to many unrelated types.
To continue your example, you could imagine a type Alien, which would probably have the same methods, but would not fit in your inheritance hierarchy.
The purpose of interfaces is to tell you what a class does, not how it does it.
This is especially important for accepting things that work differently -- each printer we attach to the PC works differently, so does each scanner, so does each external drive. If all programs needed to care about how each of them worked, you would need to recompile, say, Microsoft Office, for every model of printer that comes out.
One way to develop interfaces is to define an interface and a relative class which implements te interface a common reasonable way. Having both interface and class, you could use the interface in the case the class alreay derives from another class, otherwise a class could derived derivctly to the interface implementation.
It's not always possible, but it solves many problem.
Having a common interface is used to use different object using only the interface (collecting them to a generic list, for example).
There isn't much difference between an entirely abstract class and an interface if you only have one base type. Interfaces can't have any implementation code, but abstract classes can. In this case, abstract classes can be more flexible.
Where interfaces are really useful is that you can assign multiple interfaces to a single implementation, but you can only assign one base class.
for instance, you could have:
class Cat : IMammal, IFourLeggedAnimal
{
}
class Human: IMammal, ITwoLeggedAnimal
{
}
Now you can treat both of them as Mammals, with a "walk()" method, or you can treat them as Four or two legged animals (not necessarily mammals).
What is really useful with an interface like mammal is that you can treat an array of objects (Humans and Cats) as of being of the same type when you want them to walk, eat or run.
For instance if you ware creating a game where you have a number (objects would be created dynamically, but just for example lets say 10 cats and 1 human) of mammals on the screen (saved in a collection), and just wanted them to walk on every turn, you could simply do:
foreach(mammals m in MamalsArrayList){
{
m.walking();
}
note: I suggest you follow naming conventions and name your interfaces with "I" in front of them, so your example should be named IMammals.
without having to know weather any particular m is either a cat or a human.
Interfaces are hard to show on any particular snippet - but when you really need one you can see how useful they can be.
Of course they have other uses to (that are mentioned in other answers), I just focused on your example.
There are two issues here that are often confused. Inherited behaviour allows different 'commands' to be responded to in the same way e.g Man.walk() === Woman.walk(). Polymorphic behaviour allows the same 'command' to be responded to in different ways e.g. Animal.move() for one object may be different for Animal.move() for another, the bird will choose to fly while the slug will slide.
Now, I would argue the second of these is good while the first is not. Why? Because in OOP we should be encapsulating functionality into objects, which in turn promotes code reuse and all the other nicenesses of OOP. So rather than inheriting behaviour we should delegate it out to a shared object. If you know patterns then this is what State and Strategy are doing.
The problem lies in the fact that normally when you inherit , you get both of these behaviours mixed together. I suggest that this is more trouble than its worth and we should only be using interfaces, though sometimes we do have to make do with whatever the framework provides.
In your specific example Mammal is probably a bad interface name because it doesn't really tell me what it does and it has the potential to blowout to thousands of methods. It's better to divide interfaces into very specific cases. If you were modelling animals you might have a Moveable interface with one method, move(), to which each animal could respond by walking, running, flying, or crawling as appropriate.