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

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.

Related

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.

Composition over inheritance 2

Please have a look at the following question: Favor composition over inheritance
The accepted answerer says: " it extends Hashtable, in order to reuse its methods and to avoid reimplementing some of them using delegation". I am not sure what the answerer means by: reimplementing some of them using delegation. What does the answerer mean?
I am familiar with Delegates and the Observer design pattern.
When using composition, if you want to support a method that the underlying class has, you must define your own implementation that simply delegates (or uses) the same method on the underlying class. It can be tempting to use inheritance in this case to avoid writing that simple (delegated) method, but inheritance really should be used only when an IS-A relationship exists.
For example,
public class Foo
{
public virtual void Bar()
{
// do something
}
}
public class InheritedFromFoo : Foo
{
// we get Bar() for free!!!
}
public class ComposedWithFoo
{
private Foo _foo;
public void Bar()
{
_foo.Bar(); // delegated to the Foo instance
}
}

Suppressing Method Return in Object Oriented Language

I'm going to preface this by saying that this is by no means a major issue, more of something I haven't really heard talked about in terms of programming language design, and I was wondering if anyone had any interesting solutions.
The crux of the problem is this. Sometimes in an object-oriented language, I want to be able to modify an object via one of its methods, but return the object itself instead of what that method returns.
to give a java example:
class MyClass{
public MyClass(List<Integer> list){
//do constructor stuff
}
public MyClass(Integer i){
//what I would like to be able to do
this((new LinkedList<Integer>).add(i));
}
}
I can't create a temporary list in the second constructor, because this() must be the first line. Obviously there are a lot of ways to do this by changing the implementation, like creating an add() method that returns the object, making it the responsibility of the function constructing the object to make the list, etc.
But, considering a lot of the time you can't/don't want to modify or create a subclass (for LinkedList) and you might not want to muddy up the calling code, being able to modify and return an object in the style of ++x could be really useful. Something like
this(#(new LinkedList).add(i) to signify you want to object, not the method return. Does anyone know of a language that allows this is some concise syntactic way? If not, would this be useful at all or am I missing something fundamental here?
Wouldn't this work?
public class MyClass{
public MyClass(List<Integer> list){
//do constructor stuff
}
public static MyClass create(Integer i) {
List<Integer> list = new new LinkedList<Integer>();
list.add(i);
MyClass myClass = new MyClass(list);
return myClass;
}
}
This is somewhat common design pattern called Factory Pattern.
I think the cleanest way to solve this is to have an initialize method called from the constructors.
class MyClass
{
public MyClass(List list){
init(list);
}
public MyClass(Integer i){
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(i);
init(list);
}
protected init(List<Integer> list)
{
// do init stuff here
}
}

Multiple Inheritance: What's a good example?

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".

Where to put methods used by multiple classes?

To show an example what is this question about:
I have currently a dilemma in PHP project I'm working on. I have in mind a method that will be used by multiple classes (UIs in this case - MVC model), but I'm not sure how to represent such methods in OO design. The first thing that came into my mind was to create a class with static functions that I'd call whenever I need them. However I'm not sure if it's the right thing to do.
To be more precise, I want to work, for example, with time. So I'll need several methods that handle time. I was thinking about creating a Time class where I'd be functions that check whether the time is in correct format etc.
Some might say that I shouldn't use class for this at all, since in PHP I can still use procedural code. But I'm more interested in answer that would enlighten me how to approach such situations in OOP / OOD.
So the actual questions are: How to represent such methods? Is static function approach good enough or should I reconsider anything else?
I would recommend creating a normal class the contains this behavior, and then let that class implement an interface extracted from the class' members.
Whenever you need to call those methods, you inject the interface (not the concrete class) into the consumer. This lets you vary the two independently of each other.
This may sound like more work, but is simply the Strategy design pattern applied.
This will also make it much easier to unit test the code, because the code is more loosely coupled.
Here's an example in C#.
Interface:
public interface ITimeMachine
{
IStopwatch CreateStopwatch();
DateTimeOffset GetNow();
}
Production implementation:
public class RealTimeMachine : ITimeMachine
{
#region ITimeMachine Members
public IStopwatch CreateStopwatch()
{
return new StopwatchAdapter();
}
public DateTimeOffset GetNow()
{
return DateTimeOffset.Now;
}
#endregion
}
and here's a consumer of the interface:
public abstract class PerformanceRecordingSession : IDisposable
{
private readonly IStopwatch watch;
protected PerformanceRecordingSession(ITimeMachine timeMachine)
{
if (timeMachine == null)
{
throw new ArgumentNullException("timeMachine");
}
this.watch = timeMachine.CreateStopwatch();
this.watch.Start();
}
public abstract void Record(long elapsedTicks);
public virtual void StopRecording()
{
this.watch.Stop();
this.Record(this.watch.ElapsedTicks);
}
}
Although you say you want a structure for arbitrary, unrelated functions, you have given an example of a Time class, which has many related functions. So from an OO point of view you would create a Time class and have a static function getCurrentTime(), for example, which returns an instance of this class. Or you could define that the constuctors default behaviour is to return the current time, whichever you like more. Or both.
class DateTime {
public static function getNow() {
return new self();
}
public function __construct() {
$this->setDateTime('now');
}
public function setDateTime($value) {
#...
}
}
But apart from that, there is already a builtin DateTime class in PHP.
Use a class as a namespace. So yes, have a static class.
class Time {
public static function getCurrentTime() {
return time() + 42;
}
}
I don't do PHP, but from an OO point of view, placing these sorts of utility methods as static methods is fine. If they are completely reusable in nature, consider placing them in a utils class.