Why is an interface or an abstract class useful? (or for what?) - oop

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.

Related

Abstract and interfaces together

I am struggling to understand both abstract and interface approach. Since i get the idea what is the purpose to use one over another is clear. I was trying to found whatever example of using them both in action however all tutorials are how to use interface over abstract or vice versa showing usage either for one or another. I would really love to see practical example which could show both in action best on some real life example. Additional comments why in specific case you used one over another appreciated. Generics are very welcome to see as well in such example.
I'll propose foloowing example. We got some engine to get files from diffrent locations which could be taken using diffrent protocols as follows. I would like to understand on this example how this could be accomplished with both interfaces and abstract.
'As all of protocol has to close and open would it be good to put in abstract?
abstract class Collector
Protected Id
Protected Name
MustInherit Sub OpenConnection
MustInherit Sub CloseConection
End Class
'?
class Ftp : Collector
class Sftp: Collector
class Soap: Collector
'Interface?
Public Interface IRepository(Of T, Tkey)
Function GetAllFiles() As IEnumerable(Of T)
Function GetAllById(Tkey) as IEnumerable(Of T)
End Interface
Some key distinctions:
An abstract class can contain some implementation. An interface cannot.
In .NET, a class can not inherit from multiple base classes.
A class can implement multiple interfaces
The choice of which approach is really up to you. In general, it's a choice between the Composition pattern or Inheritance.
Composition uses Interfaces. Think of an object as having X.
Inheritance uses Classes. Think of an object as being X.
In either case, an abstract class or an interface is just a Type, through which you will access and manipulate them. For example, if you have some code that wants to perform Insert/Update/Delete operations, it doesn't need to know that the object it is operating on is a FTP client--only that the object has the ability to support these operations. (and that is exactly what IRepository specifies)
You definitely can combine both. There's no reason a concrete FtpClient class couldn't inherit from an abstract Protocol class and also implement the IRepository interface. It could even use generics!
Interfaces are great for decoupling your code, and also great for unit test mocks.
There is also a good summary of pros & cons on Wikipedia (Composition_over_inheritance). Pros:
To favor composition over inheritance is a design principle that gives the design higher flexibility. It is more natural to build business-domain classes out of various components than trying to find commonality between them and creating a family tree. For example, a gas pedal and a wheel share very few common traits, yet are both vital components in a car. What they can do and how they can be used to benefit the car is easily defined. Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members. In other words, it is better to compose what an object can do (HAS-A) than extend what it is (IS-A).
Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance. This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model. Additionally, it avoids problems often associated with relatively minor changes to an inheritance-based model that includes several generations of classes.
Cons:
One common drawback of using composition instead of inheritance is that methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods. In contrast, inheritance does not require all of the base class's methods to be re-implemented within the derived class. Rather, the derived class only needs to implement (override) the methods having different behavior than the base class methods. This can require significantly less programming effort if the base class contains many methods providing default behavior and only a few of them need to be overridden within the derived class.
I don't understand why you want to have an example combining both. Let's just say both are valid ways to build solid software architecture. They're just two tools - like having a kitchen knife and a meat cleaver. You won't necessarily use them together but see the pro's and con's when looking at the dinner you want to serve.
So usually you take abstract/MustInherit classes if you want to provide a common denominator. Sub-classes derive from the abstract one and have to implement the methods just like they would if they implemeted an interface. The good thing here is that abstract classes can provide "base logic" which can be developed centrally and all the sub-classes can make use of that. In the best case, abstract classes provide kind of "hooks" to plug in special logic in the sub-classes.
Interfaces describe what a class has to fulfill. So everything an interface defines has to be implemented in classes implementing the interface. There's no reusable logic built-in in this approach like in abstract base classes but the big "pro" for interfaces is that they don't take away the single base type you can derive from like abstract classes do. So you can derive from anything or nothing and still implement an interface. AND: You can implement multiple interfaces.
One word to the "reusable logic" with interfaces. While this is not really wroing, the .NET framework allows use to write extension methods on types (and interfaces) to attach externally developed code. This allows code reuse with interfaces like having a method implemented in there. So for example, you could write an extension method None() for the interface IEnumerable which is checking whether the enumerable is empty.
public static bool None(this IEnumerable values)
{
return !values.Any();
}
With this, None() can be used on any IEnumerable in your code base having access to the extension method (in fact, Any(), Select(), Where(), etc. are extension methods as well, lying in the System.Linq namespace).

Kotlin: Interface whereby the implementor must be a data class?

Is there an Interface that I can extend or some other way to create an Interface whereby the implementing class must be a data class? It would be useful to have access to the data class API methods such as copy().
No, copy method have unique number of parameters for every data class, so it's useless to have such interface. If all your data classes have same field - just create and implement common interface.
So I'm going to preface my answer by saying I don't have experience with Kotlin, but I have plenty of Java experience which as I understand it is similar, so unless Kotlin has a feature that helps do what you want that Java doesn't, my answer might still apply.
If I understand correctly, basically what you're trying to do is enforce that whatever class implements your interface X, must also be a subtype of Y.
My first question would be Why would you want to do this? Enforcing that X only be implemented by subtypes of Y is mixing interface and implementation, which the exact opposite of what interfaces are for.
To even enforce this, you would have to have X extend the interface of Y, either implicitly or explicitly. Since in Java (and presumably Kotlin), interfaces cannot extend objects, you have two options:
1) extend the INTERFACE of data, if it exists (which I don't think it does given what I've been reading about data classes. It sounds more like a baked in language feature than just a helpful code object)
2) Add to your interface the exact method signatures of the methods you want out of data classes. BY doing this, you've gained two things: First, you get your convenience methods whenever a data class implements your interface, and second, you still have the flexibility that interfaces are meant to provide, because now even non-data classes can implement your interface if you need them to, they just have to be sure to define the data classes interface methods manually.

What is the difference between subtyping and inheritance in OO programming?

I could not find the main difference. And I am very confused when we could use inheritance and when we can use subtyping. I found some definitions but they are not very clear.
What is the difference between subtyping and inheritance in object-oriented programming?
In addition to the answers already given, here's a link to an article I think is relevant.
Excerpts:
In the object-oriented framework, inheritance is usually presented as a feature that goes hand in hand with subtyping when one organizes abstract datatypes in a hierarchy of classes. However, the two are orthogonal ideas.
Subtyping refers to compatibility of interfaces. A type B is a subtype of A if every function that can be invoked on an object of type A can also be invoked on an object of type B.
Inheritance refers to reuse of implementations. A type B inherits from another type A if some functions for B are written in terms of functions of A.
However, subtyping and inheritance need not go hand in hand. Consider the data structure deque, a double-ended queue. A deque supports insertion and deletion at both ends, so it has four functions insert-front, delete-front, insert-rear and delete-rear. If we use just insert-rear and delete-front we get a normal queue. On the other hand, if we use just insert-front and delete-front, we get a stack. In other words, we can implement queues and stacks in terms of deques, so as datatypes, Stack and Queue inherit from Deque. On the other hand, neither Stack nor Queue are subtypes of Deque since they do not support all the functions provided by Deque. In fact, in this case, Deque is a subtype of both Stack and Queue!
I think that Java, C++, C# and their ilk have contributed to the confusion, as already noted, by the fact that they consolidate both ideas into a single class hierarchy. However, I think the example given above does justice to the ideas in a rather language-agnostic way. I'm sure others can give more examples.
A relative unfortunately died and left you his bookstore.
You can now read all the books there, sell them, you can look at his accounts, his customer list, etc. This is inheritance - you have everything the relative had. Inheritance is a form of code reuse.
You can also re-open the book store yourself, taking on all of the relative's roles and responsibilities, even though you add some changes of your own - this is subtyping - you are now a bookstore owner, just like your relative used to be.
Subtyping is a key component of OOP - you have an object of one type but which fulfills the interface of another type, so it can be used anywhere the other object could have been used.
In the languages you listed in your question - C++, Java and C# - the two are (almost) always used together, and thus the only way to inherit from something is to subtype it and vice versa. But other languages don't necessarily fuse the two concepts.
Inheritance is about gaining attributes (and/or functionality) of super types. For example:
class Base {
//interface with included definitions
}
class Derived inherits Base {
//Add some additional functionality.
//Reuse Base without having to explicitly forward
//the functions in Base
}
Here, a Derived cannot be used where a Base is expected, but is able to act similarly to a Base, while adding behaviour or changing some aspect of Bases behaviour. Typically, Base would be a small helper class that provides both an interface and an implementation for some commonly desired functionality.
Subtype-polymorphism is about implementing an interface, and so being able to substitute different implementations of that interface at run-time:
class Interface {
//some abstract interface, no definitions included
}
class Implementation implements Interface {
//provide all the operations
//required by the interface
}
Here, an Implementation can be used wherever an Interface is required, and different implementations can be substituted at run-time. The purpose is to allow code that uses Interface to be more widely useful.
Your confusion is justified. Java, C#, and C++ all conflate these two ideas into a single class hierarchy. However, the two concepts are not identical, and there do exist languages which separate the two.
If you inherit privately in C++, you get inheritance without subtyping. That is, given:
class Derived : Base // note the missing public before Base
You cannot write:
Base * p = new Derived(); // type error
Because Derived is not a subtype of Base. You merely inherited the implementation, not the type.
Subtyping doesn't have to be implemented via inheritance. Some subtyping that is not inheritance:
Ocaml's variant
Rust's lifetime anotation
Clean's uniqueness types
Go's interface
in a simple word: subtyping and inheritance both are polymorphism, (inheritance is a dynamic polymorphism - overriding). Actually, inheritance is subclassing, it means in inheritance there is no warranty to ensure capability of the subclass with the superclass (make sure subclass do not discard superclass behavior), but subtyping(such as implementing an interface and ... ), ensure the class does not discard the expected behavior.

Is it good practice for every public method to be covered by an interface?

It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.
E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.
It feels like to get cleaner code it would make sense to either:
create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)
Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?
I consider it as "overusing" the interface.
Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.
Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).
Also some classes should have restricted access to another classes, which can be done with interfaces too.
However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.
I don't think that's the purpose of interfaces. If you actually talk about the 'is-a' and 'has-a' relationship between classes, not necessarily a class needs to cover all public methods in interfaces. That's like taking the concept too far.
A class can have methods which describe it's behavior but then, there are some methods that do not exactly describe the classes' behavior but rather describe what else the class can do.
In case if a question arises about SRP regarding the 'can-do' behaviors, it is possible that the class can use a component to execute those behaviors rather than implementing within itself.
For e.g., I have a class DataGrid, why would I need to have an interface called IDataGrid which exposes all the public methods. But may be there is an additional functionality that the DataGrid can do, which is export the data. In that case I can have it implement IExportData, and implement the ExportData method, which in turn does not export the data but uses a component, say DataExportHelper, that actually does the job.
The DataGrid only passes the data to the component.
I don't think SRP will be violated in the above example.
EDIT:
I am a .Net developer, so would like to give you and example from MS library classes. For e.g., the class System.Windows.Window does not implemnt any interface that has Close() method. And I don't see why it should be a part of any presenter.
Also, it is possible that something might look seem like a code smell but not necessarily it might be wrong. Code smell itself does not mean there is a problem but that there is a possibility of problem.
I have never come across any principle or guideline in software design which mentions that all the public members of a class need to be exposed in some or the other interface. May be doing that just for the sake of it might be a bad design.
No, I would definitely not consider methods not covered by an interface a code smell.
It seems like this might be dependent on the object infrastructure you are building in, but in the infrastructures I'm familiar with, the real point of interfaces is to provide a manageable form of multiple inheritance. I consider the overuse of multiple inheritance a notable smell.
In .NET at least, abstract classes are explicitly the preferred construct for exposing abstraction (not interfaces). The .NET design guidelines say: Do favor defining classes over interfaces., with rationale described here http://msdn.microsoft.com/en-us/library/vstudio/ms229013(v=vs.100).aspx.
Even in COM (where any externally visible functionality had to be defined in an interface) there are perfectly good reasons to have non-exposed functions: limiting the visibility of implementation details. COM was originally defined in C (not C++) which lacked the richer set of access modifiers that newer languages have, but the concepts were there: published interface members were public, everything else was internal.

What is the definition of "interface" in object oriented programming

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.