Where to create interface implementation? - oop

I'm gonna ask perhaps simple an OO design question.
Imagine we inversed a dependency between two concrete classes ( Foo and Hoo ) using an interface (IHoo) where Hoo implements the interface and Foo uses that implementation.
At that point, I wondered where excatly I should attach that implementation ( Hoo ) to it's client ( Foo ). Obviously, if we add Hoo in the client class Foo, then we have not inversed the compile-time dependency ( with respect to runtime dependency ) and we have only made a bit more modular code, but not less-rigid.
So perhaps, we associate client and the interface implementation in a master ( or higher-level ) class like a controller or so? What's your approach would be ?
Thx.

Take a look at the concept of a composition root. This is where everything should be wired-up.
Factories can be used where the implementation is only known at run-time.

To complement the other answers, and to get to the question of Where to create interface implementation? the GRASP Creator pattern says (I've changed it for your context of Hoo):
A class B should be responsible for creating instances of class Hoo if one or more of the following apply:
Instances of B contain or compositely aggregate instances of Hoo
Instances of B record instances of Hoo
Instances of B closely use instances of Hoo
Instances of B have the initializing information for instances of Hoo and pass it on creation.
David Osborne's answer points out (as does GRASP Creator) you can also use a Factory.

Related

Can Coldfusion components share methods without being descendants of the same super class

We have used a homegrown version of object oriented coldfusion for a while and I'm just starting to experiment with cfc's and how it "should" be done...
If I understand correctly, cfinterface defines the signature of functions, and any class that implements that interface must have their own functions to do whats defined in the interface.
I'm kind of trying to do the opposite - the interface doesn't just define the function's signature, but also defines the logic of the function and anything that implements that interface can use its functions without having to define it itself. Does that exist besides creating subclasses?
For example, say you have classes A,B,C,D that all belong to the Animal class
A & B can walk
A & C can talk
B & D can sleep
Suppose the logic of walk, talk & sleep (if the object can do it) is the same regardless of the class doing it
Ideally, if A & B both implement the walking interface, they can walk without defining a separate walk method in each class.
Or borrowing a better example from this java multiple inheritance question
A Pegasus is a mix of a Horse and a Bird because it runs like a horse
but flies like a bird
Is that possible? (I think this is multiple inheritance?)
In short: no, an interface only defines a contract, it does not (and cannot) define functionality). Also CFML does not have the concept of multiple inheritance.
You will have to use single-inheritance and concrete implementations to effect what you need. I can't be bothered assessing your implementation-sharing requirements to work out what an approrpriate class hierarchy might be to minimise code duplication. I'm sure you can do that yourself (and it's not really part of your question anyhow).
One tactic you could try is to use mixins for your common methods. Store the common methods in a different library, and then inject them into your objects as required. So basically Mixins.cfc would implement walk(), talk(), sleep(), and you'd have an AFactory.cfc, BFactory.cfc, CFactory.cfc. When asking a factory for a new A, B or C, and the factory method injects the mixin methods before returning the instances. Obviously this is a fairly cumbersome process, and you'd want to use some sort of IoC container to manage all this.
A better question might come out of you showing us more real world examples... I suspect your domain design could perhaps stand improvement if you find yourself needing to do what your example suggests. Actual design requirements are seldom exposed with examples using animals.
You can do similar things with WireBox and its Virtual Inheritance feature:
http://wiki.coldbox.org/wiki/WireBox.cfm#Virtual_Inheritance
// Declare base CFC
map("BaseModel").to("model.base.BaseModel");
map("UserService").to("model.users.UserService").virtualInheritance("BaseModel");
It's basically very similar to what Adam described above; a base class is created, and references to it's public members are placed in the sub class.
https://github.com/ColdBox/coldbox-platform/blob/master/system/ioc/Builder.cfc#L535
There's no reason why you can't build something similar but you should know this has already been done.
Full disclosure, I am a contributing member of the *Box community.

How Go's interface programming model compares to OOP?

I have read through most of the Go tour tutorial, but I'm still unclear on how Go's interface programming model compares with OOP?
Can someone explain how I can start 'thinking in Go'?
I'm confused how you can define an interface, and then create objects based on the interface?
Does Go implicitly create an concrete implementation for you during compile time?
One of the problems OOP usually tries to solve is Polymorphism or the the ability for two different classes to have instances that behave the same. Usually in OOP this is accomplished by using inheritance. A Base class defines a minimal interface that other classes extend. All of the subclasses of Base class can be used as a Base class.
Go does the same thing not by inheritance but using interfaces. An interface is a "description" of behaviour. It is up to the individual Types in Go to satisfy this description by implementing each of the methods described in the interface. If a Type does implement all the methods described in the interface then it automatically satisfies the interface and can be cast to that interface automatically by the compiler.
Go's interface system is akin to structural typing. Consider a snippet of python code:
def foo(bar):
bar.baz(5)
In this snippet we don't know what concrete type bar is but we can say that it must have a baz method which accepts a single int argument. Note that when we're writing the class of bar we don't have to declare that we're implementing this 'interface' (having a baz method which takes an integer). We just write a baz method which works correctly when called with a single int and we can pass an instance to the foo method.
Go works in a similar manner but everything is checked at compile time. In Python if we pass our foo method an instance of a class which does not have a baz method we get a runtime exception. In Go we would define an interface with the baz method and state in the type of foo that it takes an instance of that interface. Now any type which has a baz method on a single int satisfies the type that foo requires.
Traditional (Java) OO is about class hierarchies. You model your problem with classes, some abstract, some final and interfaces. Then you provide implementations.
Go lets you go the other way around: Start with concrete types and implement your logic. If a useful abstraction emerges or is required: Pack it into an interface and refactor your code to use this interface type.

General OO design pattern

Consider the following general program structure:
Class A has an instance of Class B as a member variable
Class B has a collection member variable containing instances of class C
Events in class A are propagated to the C instances by A simply telling B about the event
What are the design patterns concerning instances of class C talking back to class A?
One option is instances of class C posting notifications to which class A subscribes. Another option is passing a reference to class A "down the chain" (from A to B then from B to each C). This latter option allows instances of C to talk directly to A.
If you mean design patterns literally (i.e. of the GoF variety) then these would be a few relevant options:
Command: pass a callback to the C items (directly or indirectly through B) so that when they want to talk back to A they can simply invoke this callback -- which can even have parameters
Iterator: B exposes a view of its aggregate collection directly to A; communication between A and C is then made directly
Mediator: Exposes notifications to which A and C might subscribe to; communication is done by posting events
Observer: What you already suggested as the first option
If on the other hand you really mean architectural patterns, then typical options are:
Your first option, A subscribing to C events. At first sight this doesn't look like an all-around good idea unless the event is extremely useful all the time, because it requires n objects to aggregate a pointer back to the callback which in the worst case they could even use just once.
Passing references to A is another option, but not a good one if you are going to pollute the public interface of A with methods just so that C can call back to it in very specific scenarios. It can be very effective if A already exposes a suitable interface, but be aware that you might need an adapter class between C calling back to A in order to not tightly couple C to A's interface.
A third option would be A iterating over (a view of) the collection provided by B directly and supplying callbacks to C instances; this has the advantages of being quite loosely coupled and that it will use the least amount of memory, but it might be a bit trickier to code.

Which class should the conversion code belong to?

If I want to cast from class Foo to another class Bar, should the code for the conversion belong in the Foo or Bar class?
Foo f
Bar b = f.ToBar()
Or:
Foo f
Bar b = Bar.FromFoo(f)
The latter could be rewritten as a constructor rather than a static method, but that's not the point of this question.
Of course in many cases, not being able to modify one of the classes makes the decision for you. For example if I had a custom class Foo and wanted to convert it to an integer.
You can look at it this way: whose concern is the conversion? Should Foo know or care that some other class called Bar, is using it in some ways? Of course not. Because, what if there are MANY other classes that use Foo, in various ways, then should Foo go ahead and take care of them too? No.
Therefore, first important point is that this functionality has to be implemented on Bar's side. And then, comes the question of secondary importance: how to implement it. Here, implementing it as a constructor, as others have pointed out, is more logical and inline with oop principle.
The operation should typically live on the object it affects, so in this case it would be f.ToBar().

Inheritance and interfaces

This is somewhat of a follow-up question to this question.
Suppose I have an inheritance tree as follows:
Car -> Ford -> Mustang -> MustangGT
Is there a benefit to defining interfaces for each of these classes? Example:
ICar -> IFord -> IMustang -> IMustangGT
I can see that maybe other classes (like Chevy) would want to implement Icar or IFord and maybe even IMustang, but probably not IMustangGT because it is so specific. Are the interfaces superfluous in this case?
Also, I would think that any class that would want to implement IFord would definitely want to use its one inheritance by inheriting from Ford so as not to duplicate code. If that is a given, what is the benefit of also implementing IFord?
In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.
And in response to the first part of your question, I would recommend against creating an interface for each of your classes. This would unnecessarily clutter your class structure. If you find you need an interface you can always add it later. Hope this helps!
Adam
I also agree with adamalex's response that interfaces should be shared by classes that should respond to certain methods.
If classes have similar functionality, yet are not directly related to each other in an ancestral relationship, then an interface would be a good way to add that function to the classes without duplicating functionality between the two. (Or have multiple implementations with only subtle differences.)
While we're using a car analogy, a concrete example. Let's say we have the following classes:
Car -> Ford -> Escape -> EscapeHybrid
Car -> Toyota -> Corolla -> CorollaHybrid
Cars have wheels and can Drive() and Steer(). So those methods should exist in the Car class. (Probably the Car class will be an abstract class.)
Going down the line, we get the distinction between Ford and Toyota (probably implemented as difference in the type of emblem on the car, again probably an abstract class.)
Then, finally we have a Escape and Corolla class which are classes that are completely implemented as a car.
Now, how could we make a Hybrid vehicle?
We could have a subclass of Escape that is EscapeHybrid which adds a FordsHybridDrive() method, and a subclass of Corolla that is CorollaHybrid with ToyotasHybridDrive() method. The methods are basically doing the same thing, but yet we have different methods. Yuck. Seems like we can do better than that.
Let's say that a hybrid has a HybridDrive() method. Since we don't want to end up having two different types of hybrids (in a perfect world), so we can make an IHybrid interface which has a HybridDrive() method.
So, if we want to make an EscapeHybrid or CorollaHybrid class, all we have to do is to implement the IHybrid interface.
For a real world example, let's take a look at Java. A class which can do a comparison of an object with another object implements the Comparable interface. As the name implies, the interface should be for a class that is comparable, hence the name "Comparable".
Just as a matter of interest, a car example is used in the Interfaces lesson of the Java Tutorial.
You shouldn't implement any of those interfaces at all.
Class inheritance describes what an object is (eg: it's identity). This is fine, however most of the time what an object is, is far less important than what an object does. This is where interfaces come in.
An interface should describe what an object does), or what it acts like. By this I mean it's behavior, and the set of operations which make sense given that behaviour.
As such, good interface names should usually be of the form IDriveable, IHasWheels, and so on. Sometimes the best way to describe this behaviour is to reference a well-known other object, so you can say "acts like one of these" (eg: IList) but IMHO that form of naming is in the minority.
Given that logic, the scenarios where interface inheritance makes sense are completely and entirely different from the scenarios where object inheritance makes sense - often these scenarios don't relate to eachother at all.
Hope that helps you think through the interfaces you should actually need :-)
I'd say only make an interface for things you need to refer to. You may have some other classes or functions that need to know about a car, but how often will there be something that needs to know about a ford?
Don't build stuff you don't need. If it turns out you need the interfaces, it's a small effort to go back and build them.
Also, on the pedantic side, I hope you're not actually building something that looks like this hierarchy. This is not what inheritance should be used for.
Create it only once that level of functionality becomes necessary.
Re-factoring Code is always on on-going process.
There are tools available that will allow you to extract to interface if necessary.
E.G. http://geekswithblogs.net/JaySmith/archive/2008/02/27/refactor-visual-studio-extract-interface.aspx
Make an ICar and all the rest (Make=Ford, Model=Mustang, and stuff) as members of a class that implements the interface.
You might wanna have your Ford class and for example GM class and both implement ICar in order to use polymorphism if you don't wanna go down the route of checking Make == Whatever, that's up to your style.
Anyway - In my opinion those are attributes of a car not the other way around - you just need one interface because methods are common: Brake, SpeedUp, etc.
Can a Ford do stuff that other cars cannot? I don't think so.
I woudl create the first two levels, ICar and IFord and leave the second level alone until I need an interface at that second level.
Think carefully about how your objects need to interact with each other within your problem domain, and consider if you need to have more than one implementation of a particular abstract concept. Use Interfaces to provide a contract around a concept that other objects interact with.
In your example, I would suggest that Ford is probably a Manufacturer and Mustang is a ModelName Value used by the Manufacturer Ford, therefore you might have something more like:
IVehichle -> CarImpl, MotorbikeImpl - has-a Manufacturer has-many ModelNames
In this answer about the difference between interface and class, I explained that:
interface exposes what a concept is (in term of "what is" valid, at compilation time), and is used for values (MyInterface x = ...)
class exposes what a concept does (actually executed at runtime), and is used for values or for objects (MyClass x or aMyClass.method() )
So if you need to store into a 'Ford' variable (notion of 'value') different sub-classes of Ford, create an IFord. Otherwise, do not bother until you actually need it.
That is one criteria: if it is not met, IFord is probably useless.
If it is met, then the other criteria exposed in the previous answers apply: If a Ford has a richer API than a Car, an IFord is useful for polymorphisms purpose. If not, ICar is enough.
In my view interfaces are a tool to enforce a requirement that a class implement a certain signature, or (as I like to think of it) a certain "Behavior" To me I think if the Capital I at the beginning of my onterface names as a personal pronoun, and I try to name my interfaces so they can be read that way... ICanFly, IKnowHowToPersistMyself IAmDisplayable, etc... So in your example, I would not create an interface to Mirror the complete public signature of any specific class. I would analyze the public signature (the behavior) and then separate the members into smaller logical groups (the smaller the better) like (using your example) IMove, IUseFuel, ICarryPassengers, ISteerable, IAccelerate, IDepreciate, etc... And then apply those interfaces to whatever other classes in my system need them
In general, the best way to think about this (and many questions in OO) is to think about the notion of a contract.
A contract is defined as an agreement between two (or more) parties, that states specific obligations each party must meet; in a program, this is what services a class will provide, and what you have to provide the class in order to get the services. An interface states a contract that any class implementing the interface must satisfy.
With that in mind, though, your question somewhat depends on what language you're using and what you want to do.
After many years of doing OO (like, oh my god, 30 years) I would usually write an interface for every contract, especially in Java, because it makes tests so much easier: if I have an interface for the class, I can build mock objects easily, almost trivially.
Interfaces are intended to be a generic public API, and users will be restricted to using this public API. Unless you intend users to be using the type-specific methods of IMustangGT, you may want to limit the interface hierarchy to ICar and IExpensiveCar.
Only inherit from Interfaces and abstract classes.
If you have a couple of classes wich are almost the same, and you need to implement the majority of methods, use and Interface in combination with buying the other object.
If the Mustang classes are so different then not only create an interface ICar, but also IMustang.
So class Ford and Mustang can inherit from ICar, and Mustang and MustangGT from ICar and IMustang.
If you implement class Ford and a method is the same as Mustang, buy from Mustang:
class Ford{
public function Foo(){
...
Mustang mustang = new Mustang();
return mustang.Foo();
}