Multiple Inheritance: What's a good example? - oop

I'm trying to find a good example for the use of multiple inheritance what cannot be done with normal interfaces.
I think it's pretty hard to find such an example which cannot be modeled in another way.
Edit: I mean, can someone name me a good real-world example of when you NEED to use multiple inheritance to implement this example as clean as possible. And it should not make use of multiple interfaces, just the way you can inherit multiple classes in C++.

The following is a classic:
class Animal {
public:
virtual void eat();
};
class Mammal : public Animal {
public:
virtual void breathe();
};
class WingedAnimal : public Animal {
public:
virtual void flap();
};
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {
};
Source: wiki.

One example where multiple class inheritance makes sense is the Observer pattern. This pattern describes two actors, the observer and the observable, and the former wants to be notified when the latter changes its object state.
A simplified version for notifying clients can look like this in C#:
public abstract class Observable
{
private readonly List<IObserver> _observers = new List<IObserver>();
// Objects that want to be notified when something changes in
// the observable can call this method
public void Subscribe(IObserver observer)
{
_observers.Add(observer);
}
// Subclasses can call this method when something changes
// to notify all observers
protected void Notify()
{
foreach (var observer in _observers)
observer.Notify();
}
}
This basically is the core logic you need to notify all the registered observers. You could make any class observable by deriving from this class, but as C# does only support single class inheritance, you are limited to not derive from another class. Something like this wouldn't work:
public class ImportantBaseClass { /* Members */ }
public class MyObservableSubclass : ImportantBaseClass, Observable { /* Members */ }
In these cases you often have to replicate the code that makes subclasses observable in all of them, basically violating the Don't Repeat Yourself and the Single Point of Truth principles (if you did MVVM in C#, think about it: how often did you implement the INotifyPropertyChanged interface?). A solution with multiple class inheritance would be much cleaner in my opinion. In C++, the above example would compile just fine.
Uncle Bob wrote an interesting article about this, that is where I got the example from. But this problem often applies to all interfaces that are *able (e.g. comparable, equatable, enumerable, etc.): a multiple class inheritance version is often cleaner in these cases, as stated by Bertrand Meyer in his book "Object-Oriented Software Construction".

Related

How to make interface implementors that are not sub classes of its abstract class behave like abstract class of that interface?

I want to explain my question with an example. Lets say that i have an interface:
interface IActionPerformer
{
bool IsReadyToExecuteAction();
void Action();
IActionImplementor GetImplementor();
}
And an implementor for Action() method. I don't know if it is the right or wrong way to do so, but anyways, keep reading i will explain my purpose. Implementor:
interface IActionImplementor
{
void Action();
}
And an abstract class that implements IActionPerformer:
abstract class ActionPerformerBase: IActionPerformer
{
private IActionImplementor _implementor;
public abstract bool IsReadyToExecuteAction();
public IActionImplementor GetImplementor()
{
return _implementor;
}
public void Action()
{
if (IsReadyToExecuteAction())
{
GetImplementor().Action();
}
}
protected ActionPerformerBase(IActionImplementor implementor)
{
this._implementor = implementor;
}
}
Now sub classes which inherit from this abstract class, execute the actual action only if it is ready to execute.
But let's say that i have an object in my software, that inherits from a different super class. But at the same time, this object must behave like an IActionPerformer. I mean this object must implement IActionPerformer interface, like:
class SomeOtherSubClass : SomeOtherSuperClass, IActionPerformer
At this point, i want to execute Action() method with controlling if it is ready to execute.
I thought invoking method with another object might be a solution. I mean, a controller or handler object gets interface as a parameter and invokes method the way i want. Like:
IActionInvoker.Invoke(IActionPerformer performer)
{
if (performer.IsReadyToExecuteAction())
{
performer.Action();
}
}
Or every IActionPerformer implementor has a IActionPerformer or ActionPerformerBase(it feels better) object which handles the real control like:
class SomeOtherSubClass : SomeOtherSuperClass, IActionPerformer
{
ActionPerformerBase _realHandler;
public bool IsReadyToExecuteAction()
{
return _realHandler.IsReadyToExecuteAction();
}
public void Action()
{
_realHandler.Action();
}
.
.
.
}
//This is the one get the job done actually.
class RealHandlerOfSomething : ActionPerformerBase
I might not be that clear trying to explain my question. I'm new to concepts like abstraction, design patterns and sort of stuff like that. And trying to figure out them. This one looks like a decorator, it is a IActionPerformerand it has a IActionPerformer. But when i study decorator pattern, i saw it is like going from shell to the core, i mean every object executes its method and the wrapped objects method. It is a bit different in my example, i mean question. Is this what we call as "encapsulation"? Or do i have big issues understanding the concepts?
I hope i explained myself clearly. Thanks for everyone reading, trying to help.
Have a nice day/night.
As Design Patterns states in chapter one:
Favor object composition over class inheritance
This was in 1994. Inheritance makes things complicated. The OP is another example.
In the following, I'll keep IActionPerformer and ActionPerformerBase as is. Since inheritance is isomorphic to composition, everything you can do with inheritance, you can also do with composition - and more, such as emulating multiple inheritance.
Here's how you can implement the IActionPerformer interface from another subclass, and still reuse ActionPerformerBase:
public class SomeOtherSubClass : SomeOtherSuperClass, IActionPerformer
{
private readonly ActionPerformerBase #base;
public SomeOtherSubClass(ActionPerformerBase #base)
{
this.#base = #base;
}
public void Action()
{
// Perhaps do something before calling #base...
#base.Action();
// Perhaps do something else after calling #base...
}
// Other methods of IActionPerformer go here, possibly following the same pattern...
}
SomeOtherSubClass composes with any ActionPerformerBase, and since ActionPerformerBase has the desired functionality, that functionality is effectively reused.
Once you've figured out how to use composition for reuse instead of inheritance, do yourself a favour and eliminate inheritance from your code base. Trust me, you don't need it. I've been designing and writing production code for more than a decade without inheritance.

How to deal with "optional interfaces"?

"Optional interface" is probably not a standard term, so let me give an example. Suppose I have:
interface Car {
start();
honk();
}
Now I can have like HondaCar, PriusCar, etc., implementations. Yay! But what if honking is not all that important to me or my users, so I decide to do something like this:
interface Car {
start();
canHonk(); // return true if honking is supported
honk(); // undefined behavior of canHonk is false
}
So this is what I'm calling an "optional interface", because actually supporting honk is optional. It still seems like a fine, well-defined interface, but another way you could've expressed this is by separating this into two interfaces:
interface Car {
start();
}
interface Honkable {
honk();
}
Now, if user code really needs to do some honking, you must pass it a Honkable. If it's optional, it can take a null pointer. And if it doesn't care about honking at all, it can ignore Honkable completely. However, this does put more onus on the user code to manage all this.
So, I've listed some pros and cons that I see, but I'm curious what others think. Which is the preferable pattern in which situations?
Composition over Inheritance, our subject here, is an important OOP principle. It tells us to define our objects by their functions. Which means, your second approach is the best practice. Do it like:
public class SomeCar: ICar, IHonk {}
public Interface ICar {}
public Interface IHonk {}
Design for capability instead of identity.
Two separate interfaces is the way to go in my opinion
If you want to honk, implement the interface
As others have mentioned, separate interfaces are a better solution here. It is also worth noting that it conforms to the Interface Segregation Principle from SOLID.
However, another approach would be to use a feature container:
public class FeatureContainer {
// ...
public bool isAvailable<T>() {
// ...
}
public T getFeatureOrNull<T>() {
// ...
}
}
and then have for example:
public abstract class Car : FeatureContainer {
// ...
};
public class SomeCar : Car {
public SomeCar()
: base(/* instantiate all implementations of supported interfaces */)
{}
}
so then you could have:
Car aCar = getSomeCar();
if (aCar.isAvailable<Honkable>()) {
Honkable h = aCar.getFeatureOrNull<Honkable>();
h.honk();
}
This can have of course numerous syntactical variations depending on language and desired semantics.

Why does Wikipedia say "Polymorphism is not the same as method overloading or method overriding."

I have looked around and could not find any similar question.
Here is the paragraph I got from Wikipedia:
Polymorphism is not the same as method overloading or method overriding. Polymorphism is only concerned with the application of specific implementations to an interface or a more generic base class. Method overloading refers to methods that have the same name but different signatures inside the same class. Method overriding is where a subclass replaces the implementation of one or more of its parent's methods. Neither method overloading nor method overriding are by themselves implementations of polymorphism.
Could anyone here explain it more clearly, especially the part "Polymorphism is not the same as method overriding"? I am confused now. Thanks in advance.
Polymorphism (very simply said) is a possibility to use a derived class where a base class is expected:
class Base {
}
class Derived extends Base {
}
Base v = new Derived(); // OK
Method overriding, on the other hand, is as Wiki says a way to change the method behavior in a derived class:
class Shape {
void draw() { /* Nothing here, could be abstract*/ }
}
class Square extends Shape {
#Override
void draw() { /* Draw the square here */ }
}
Overloading is unrelated to inheritance, it allows defining more functions with the same name that differ only in the arguments they take.
You can have polymorphism in a language that does not allow method overriding (or even inheritance). e.g. by having several different objects implement the same interface. Polymorphism just means that you can have different concrete implementations of the same abstract interface. Some languages discourage or disallow inheritance but allow this kind of polymorphism in the spirit of programming with abstractions.
You could also theoretically have method overriding without polymorphism in a language that doesn't allow virtual method dispatch. The effect would be that you could create a new class with overridden methods, but you wouldn't be able to use it in place of the parent class. I'm not aware of any mainstream language that does this.
Polymorphism is not about methods being overridden; it is about the objects determining the implementation of a particular process. An easy example - but by no means the only example - is with inheritance:
A Novel is a type of Book. It has most of the same methods, and everything you can do to a Book can also be done to a Novel. Therefore, any method that accepts a Book as an argument can also deal with a Novel as an argument. (Example would include .read(), .write(), .burn()). This is, per se, not referring to the fact that a Novel can overwrite a Book method. Instead, it is referring to a feature of abstraction. If a professor assigns a Book to be read, he/she doesn't care how you read it - just that you do. Similarly, a calling program doesn't care how an object of type Book is read, just that it is. If the object is a Novel, it will be read as a Novel. If it is not a novel but is still a book, it will be read as a Book.
Book:
private void read(){
#Read the book.
}
Novel:
private void read(){
#Read a book, and complain about how long it is, because it's a novel!
}
Overloading methods is just referring to having two methods with the same name but a different number of arguments. Example:
writeNovel(int numPages, String name)
writeNovel(String name)
Overloading is having, in the same class, many methods with the same name, but differents parameters.
Overriding is having, in an inherited class, the same method+parameters of a base class. Thus, depending on the class of the object, either the base method, or the inherited method will be called.
Polymorphism is the fact that, an instance of an inherited class can replace an instance of a base class, when given as a parameters.
E.g. :
class Shape {
public void draw() {
//code here
}
public void draw(int size) {
//this is overloading
}
}
class Square inherits Shape {
public void draw() {
//some other code : this is overriding
}
public void draw(color c) {
//this is overloading too
}
}
class Work {
public myMethod(Shape s) {
//using polymophism, you can give to this method
//a Shape, but also a Square, because Square inherits Shape.
}
}
See it ?
Polymorphing is the fact that, the same object, can be used as an instance of its own class, its base class, or even as an interface.
Polymorphism refers to the fact that an instance of a type can be treated just like any instance of any of its supertypes. Polymorphism means 'many forms'.
Say you had a type named Dog. You then have a type named Spaniel which inherits from Dog. An instance of Spaniel can be used wherever a Dog is used - it can be treated just like any other Dog instance. This is polymorphism.
Method overriding is what a subclass may do to methods in a base class. Dog may contain a Bark method. Spaniel can override that method to provide a more specific implementation. Overriding methods does not affect polymorphism - the fact that you've overriden a Dog method in Spaniel does not enable you to or prevent you from treating a Spaniel like a dog.
Method overloading is simply the act of giving different methods which take different parameters the same name.
I hope that helps.
Frankly:
Polymorphism is using many types which have specific things in common in one implementation which only needs the common things, where as method overloading is using one implementation for each type.
When you override a method, you change its implementation. Polymorphism will use your implementation, or a base implementation, depending on your language (does it support virtual methods?) and depending on the class instance you've created.
Overloading a method is something else, it means using the same method with a different amount of parameters.
The combination of this (overriding), plus the possibility to use base classes or interfaces and still call an overriden method somewhere up the chain, is called polymorphism.
Example:
interface IVehicle
{
void Drive();
}
class Car : IVehicle
{
public Drive() { /* drive a car */ }
}
class MotorBike : IVehicle
{
public Drive() { /* drive a motorbike */ }
}
class Program
{
public int Main()
{
var myCar = new Car();
var myMotorBike = new MotorBike();
this.DriveAVehicle(myCar); // drive myCar
this.DriveAVehicle(myMotorBike); // drive a motobike
this.DriveAVhehicle(); // drive a default car
}
// drive any vehicle that implements IVehicle
// this is polymorphism in action
public DriveAVehicle(IVehicle vehicle)
{
vehicle.Drive();
}
// overload, creates a default car and drives it
// another part of OO, not directly related to polymorphism
public DriveAVehicle()
{
// typically, overloads just perform shortcuts to the method
// with the real implemenation, making it easier for users of the class
this.DriveAVehicle(new Car());
}
}

When is an "interface" useful?

OOP interfaces.
In my own experience I find interfaces very useful when it comes to design and implement multiple inter-operating modules with multiple developers. For example, if there are two developers, one working on backend and other on frontend (UI) then they can start working in parallel once they have interfaces finalized. Thus, if everyone follows the defined contract then the integration later becomes painless. And thats what interfaces precisely do - define the contract!
Basically it avoids this situation :
Interfaces are very useful when you need a class to operate on generic methods implemented by subclasses.
public class Person
{
public void Eat(IFruit fruit)
{
Console.WriteLine("The {0} is delicious!",fruit.Name);
}
}
public interface IFruit
{
string Name { get; }
}
public class Apple : IFruit
{
public string Name
{
get { return "Apple"; }
}
}
public class Strawberry : IFruit
{
public string Name
{
get { return "Strawberry"; }
}
}
Interfaces are very useful, in case of multiple inheritance.
An Interface totally abstracts away the implementation knowledge from the client.
It allows us to change their behavior dynamically. This means how it will act depends on dynamic specialization (or substitution).
It prevents the client from being broken if the developer made some changes
to implementation or added new specialization/implementation.
It gives an open way to extend an implementation.
Programming language (C#, java )
These languages do not support multiple inheritance from classes, however, they do support multiple inheritance from interfaces; this is yet another advantage of an interface.
Basically Interfaces allow a Program to change the Implementation without having to tell all clients that they now need a "Bar" Object instead of a "Foo" Object. It tells the users of this class what it does, not what it is.
Example:
A Method you wrote wants to loop through the values given to it. Now there are several things you can iterate over, like Lists, Arrays and Collections.
Without Interfaces you would have to write:
public class Foo<T>
{
public void DoSomething(T items[])
{
}
public void DoSomething(List<T> items)
{
}
public void DoSomething(SomeCollectionType<T> items)
{
}
}
And for every new iteratable type you'd have to add another method or the user of your class would have to cast his data. For example with this solution if he has a Collection of FooCollectionType he has to cast it to an Array, List or SomeOtherCollectionType.
With interfaces you only need:
public class Foo<T>
{
public void DoSomething(IEnumerable<T> items)
{
}
}
This means your class only has to know that, whatever the user passes to it can be iterated over. If the user changes his SomeCollectionType to AnotherCollectionType he neither has to cast nor change your class.
Take note that abstract base classes allow for the same sort of abstraction but have some slight differences in usage.

Bridge Pattern - Composition or Aggregation?

I'm reading some books about Design Patterns and while some describe the relation between the abstraction and the implementation as a composition, some describe it as an aggregation. Now I wonder: is this dependant on the implementation? On the language? Or context?
The terms "composition" and "aggregation" mean more or less the same thing and may be used interchangeably. Aggregation may be used more frequently when describing container classes such as lists, dynamic arrays, maps, and queues where the elements are all of the same type; however, both terms may be found to describe classes defined in terms of other classes, regardless of whether those types are homogenous (all of the same type) or heterogenous (objects of different types).
To make this clearer:
class Car {
// ...
private:
Engine engine;
Hood hood;
};
// The car is *composed* of an engine and a hood. Hence, composition. You are
// also bringing together (i.e. *aggregating*) an engine and hood into a car.
The relationship between abstraction and implementation typically implies inheritance, rather than composition/aggregation; typically the abstraction is an interface or virtual base class, and the implementation is a fully concrete class that implements the given interface. But, to make things confusing, composition/aggregation can be a part of the interface (because, for example, you may need to set/get the objects that are used as building blocks), and they are also an approach to implementation (because you might use delegation to provide the definition for methods in your implementation).
To make this clearer:
interface Car {
public Engine getEngine();
public Hood getHood();
public void drive();
}
// In the above, the fact that a car has these building blocks
// is a part of its interface (the abstraction).
class HondaCivic2010 implements Car {
public void drive(){ getEngine().drive(); }
// ...
}
// In the above, composition/delegation is an implementation
// strategy for providing the drive functionality.
Since you have tagged your question "bridge", I should point out that the definition of the bridge pattern is a pattern where you use composition rather than inheritance to allow for variation at multiple different levels. An example that I learned at college... using inheritance you might have something like:
class GoodCharacter;
class BadCharacter;
class Mage;
class Rogue;
class GoodMage : public GoodCharacter, Mage;
class BadMage : public BadCharacter, Mage;
class GoodRogue : public GoodCharacter, Rogue;
class BadRogue : public BadCharacter, Rogue;
As you can see, this kind of thing goes pretty crazy, and you get a ridiculous number of classes. The same thing, with the bridge pattern, would look like:
class Personality;
class GoodPersonality : public Personality;
class BadPersonality : public Personality;
class CharacterClass;
class Mage : public CharacterClass;
class Rogue : public CharacterClass;
class Character {
public:
// ...
private:
CharacterClass character_class;
Personality personality;
};
// A character has both a character class and a personality.
// This is a perfect example of the bridge pattern, and we've
// reduced MxN classes into a mere M+N classes, and we've
// arguably made the system even more flexible than before.
the bridge pattern must use delegation (aggregation/composition and not inheritance). from the gang-of-four book:
Use the Bridge pattern when
* you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.
* both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
* changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.
* (C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.
* you have a proliferation of classes as shown earlier in the first Motivation diagram. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations" [RBP+91] to refer to such class hierarchies.
* you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien's String class [Cop92], in which multiple objects can share the same string representation (StringRep).
Standard UML of Bridge pattern clears out all air around the confusion. Below is an explanation with a brief example to clear the air around this.
Apologies for this lengthy code, best way is to copy this code to Visual Studio to easily understand it.
Read through the explanation written at the end of code
interface ISpeak
{
void Speak();
}
class DogSpeak : ISpeak
{
public void Speak()
{
Console.WriteLine("Dog Barks");
}
}
class CatSpeak : ISpeak
{
public void Speak()
{
Console.WriteLine("Cat Meows");
}
}
abstract class AnimalBridge
{
protected ISpeak Speech;
protected AnimalBridge(ISpeak speech)
{
this.Speech = speech;
}
public abstract void Speak();
}
class Dog : AnimalBridge
{
public Dog(ISpeak dogSpeak)
: base(dogSpeak)
{
}
public override void Speak()
{
Speech.Speak();
}
}
class Cat : AnimalBridge
{
public Cat(ISpeak catSpeak)
: base(catSpeak)
{
}
public override void Speak()
{
Speech.Speak();
}
}
-- ISpeak is the abstraction that bot Dog and Cat has to implement
-- Decoupled Dog and Cat classes by introducing a bridge "Animal" that is composed of ISpeak
-- Dog and Cat classes extend Animal class and thus are decoupled from ISpeak.
Hope this clarifies