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

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.

Related

can overriding of a method be prevented by downcasting to a superclass?

I'm trying to understand whether the answer to the following question is the same in all major OOP languages; and if not, then how do those languages differ.
Suppose I have class A that defines methods act and jump; method act calls method jump. A's subclass B overrides method jump (i.e., the appropriate syntax is used to ensure that whenever jump is called, the implementation in class B is used).
I have object b of class B. I want it to behave exactly as if it was of class A. In other words, I want the jump to be performed using the implementation in A. What are my options in different languages?
For example, can I achieve this with some form of downcasting? Or perhaps by creating a proxy object that knows which methods to call?
I would want to avoid creating a brand new object of class A and carefully setting up the sharing of internal state between a and b because that's obviously not future-proof, and complicated. I would also want to avoid copying the state of b into a brand new object of class A because there might be a lot of data to copy.
UPDATE
I asked this question specifically about Python, but it seems this is impossible to achieve in Python and technically it can be done... kinda..
It appears that apart from technical feasibility, there's a strong argument against doing this from a design perspective. I'm asking about that in a separate question.
The comments reiterated: Prefer composition over inheritance.
Inheritance works well when your subclasses have well defined behavioural differences from their superclass, but you'll frequently hit a point where that model gets awkward or stops making sense. At that point, you need to reconsider your design.
Composition is usually the better solution. Delegating your object's varying behaviour to a different object (or objects) may reduce or eliminate your need for subclassing.
In your case, the behavioural differences between class A and class B could be encapsulated in the Strategy pattern. You could then change the behaviour of class A (and class B, if still required) at the instance level, simply by assigning a new strategy.
The Strategy pattern may require more code in the short run, but it's clean and maintainable. Method swizzling, monkey patching, and all those cool things that allow us to poke around in our specific language implementation are fun, but the potential for unexpected side effects is high and the code tends to be difficult to maintain.
What you are asking is completely unrelated/unsupported by OOP programming.
If you subclass an object A with class B and override its methods, when a concrete instance of B is created then all the overriden/new implementation of the base methods are associated with it (either we talk about Java or C++ with virtual tables etc).
You have instantiated object B.
Why would you expect that you could/would/should be able to call the method of the superclass if you have overriden that method?
You could call it explicitely of course e.g. by calling super inside the method, but you can not do it automatically, and casting will not help you do that either.
I can't imagine why you would want to do that.
If you need to use class A then use class A.
If you need to override its functionality then use its subclass B.
Most programming languages go to some trouble to support dynamic dispatch of virtual functions (the case of calling the overridden method jump in a subclass instead of the parent class's implementation) -- to the degree that working around it or avoiding it is difficult. In general, specialization/polymorphism is a desirable feature -- arguably a goal of OOP in the first place.
Take a look at the Wikipedia article on Virtual Functions, which gives a useful overview of the support for virtual functions in many programming languages. It will give you a place to start when considering a specific language, as well as the trade-offs to weigh when looking at a language where the programmer can control how dispatch behaves (see the section on C++, for example).
So loosely, the answer to your question is, "No, the behavior is not the same in all programming languages." Furthermore, there is no language independent solution. C++ may be your best bet if you need the behavior.
You can actually do this with Python (sort of), with some awful hacks. It requires that you implement something like the wrappers we were discussing in your first Python-specific question, but as a subclass of B. You then need to implement write-proxying as well (the wrapper object shouldn't contain any of the state normally associated with the class hierarchy, it should redirect all attribute access to the underlying instance of B.
But rather than redirecting method lookup to A and then calling the method with the wrapped instance, you'd call the method passing the wrapper object as self. This is legal because the wrapper class is a subclass of B, so the wrapper instance is an instance of the classes whose methods you're calling.
This would be very strange code, requiring you to dynamically generate classes using both IS-A and HAS-A relationships at the same time. It would probably also end up fairly fragile and have bizarre results in a lot of corner cases (you generally can't write 100% perfect wrapper classes in Python exactly because this sort of strange thing is possible).
I'm completely leaving aside weather this is a good idea or not.

How to move away from Inheritance

I've searched in here and other forums and couldn't find a good answer..
I kind of know that Extending classes isn't the best of practices. And that I should use Interfaces more. my problem is that usually I start creating Interfaces and then move to Abstract classes because there's always some functionality that I want implemented on a super class so that I don't have to replicate it in every child classes.
For instance, I have a Vehicle class and the Car and Bike child classes. a lot of functionality could be implemented on the Vehicle class, such as Move() and Stop(), so what would be the best practice to keep the architecture clean, avoid code repetition and use Interfaces instead of Inheritance?
Thanks a lot!
(if you have no idea why I'm asking this you may read this interesting article: http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html)
Inheritance ('extending classes') imposes significant limitations on class design and I'm not sure the use of interfaces as a replacement for inheritance is the best idea since it fails the DRY test.
These days, Composition is favored over Inheritance, so you might consider this post: Prefer composition over inheritance?
Interesting question. Everyone has different approaches. But it all based on personal experience and choice.
Usually, i start with an interface, then let an abstract class inherit that interface. And implement common actions there, and let others to be implemented by who ever inherits this class.
This give few advantageous based on by experience,
1.During function calls you can pass the elements as interface type or abstract class type.
2.Common variables such as ID, Names etc can be put on abstract class.
3.Easy for maintenance. For example, if you want to implement a new interface, then just implement in the abstract quickly.
If you keep in mind fundamental difference between interfaces and classes it will make it easier to decide which one to use. The difference is that interfaces represent just a protocol (usually behavioral) between objects involved, while abstract classes represent some unfinished constructions that involve some parts (data). In car example, interface is essentially a blueprint for the generic car. And abstract class would be like prefabricated specific model car body that needs to be filled with remaining parts to get final product. Interfaces don't even have to be in Java - it will not change anything - still blueprint.
Typically you would use abstract class within your specific implementation framework to provide its consumers with some basic functionality. If you just state that you never use abstract class in favor of interface - it's plain wrong from practical standpoint. What if you need 10 implementations of the same interface with 90% of the same code. Replicate code 10 times? Ok, may be you would use abstract class here but put interface on top of it. But why would you do that if you never intend to offer your class hierarchy to external consumers?
I am using word external in very wide sense - it can be just different package in your project or remote consumer.
Ultimately, many of those things are preferences and personal experiences, but I disagree with most blanket statements like extends is evil. I also prefer not to use extra classes (interfaces or abstract) unless it is required by specific parts of the design.
Just my two cents.
Inheritance allows code reuse and substitutability, but restricts polymorphism. Composition allows code reuse but not substitutability. Interfaces allow substitutability but not code reuse.
The decision of whether to use inheritance, composition, or interfaces, boils down to a few simple principles:
If one needs both code reuse and substitutability, and the restrictions imposed on polymorphism aren't too bad, use inheritance.
If one needs code reuse, but not substitutability, use composition.
If one needs substitutability, but not code reuse, or if the restrictions inheritance would impose upon polymorphism would be worse than duplicated code, use interfaces.
If one needs substitutability and code reuse, but the restrictions imposed by polymorphism would be unacceptable, use interfaces to wrap encapsulated objects.
If one needs substitutability and code reuse, and the restrictions imposed by polymorphism would not pose any immediate problem but might be problematic for future substitutable classes, derive a model base class which implements an interface, and have those classes that can derive from it do so. Avoid using variables and parameters of the class type, though--use the interface instead. If you do that, and there is a need for a substitutable class which cannot very well derive from the model base class, the new class can implement the interface without having to inherit from the base; if desired, it may implement the interface by wrapping an encapsulated instance of a derivative of the model type.
Judgment may be required in deciding whether future substitutable classes may have difficulty deriving from a base class. I tend to think approach #5 often offers the best of all worlds, though, when substitutability is required. It's often cheaper than using interfaces alone, and not much more expensive than using inheritance alone. If there is a need for future classes which are substitutable but cannot be derived from the base, it may be necessary to convert the code to use approach #5. Using approach #5 from the get-go would avoid having to refactor the code later. (Of course, if it's never necessary to substitute a class that can't derive from the base, the extra cost--slight as it may be--may end up being unnecessary).
Agree with tofutim - in your current example, move and stop on Vehicle is reasonable.
Having read the article - I think it's using powerful language to push a point... remember - inheritance is a tool to help get a job done.
But if we go with the assumption that for whatever reasons you can't / won't use the tool in this case, you can start by breaking it down into small interfaces with helper objects and/or visitors...
For example -
Vehicle types include submarine, boat, plane, car and bike. You could break it down into interfaces...
IMoveable
+ Forward()
+ Backward()
+ Left()
+ Right()
IFloatable
+ Dock()
ISink()
+ BlowAir()
IFly()
+ Takeoff()
+ Land()
And then your classes can aggregate the plethora of interfaces you've just defined.
The problem is though that you may end up duplicating some code in the car / bike class for IMoveable.Left() and IMoveable.Right(). You could factor this into a helper method and aggregate the helper... but if you follow it to its logical conclusion, you would still end up refactoring many things back into base classes.
Inheritance and Aggregation are tools... neither of which are "evil".
Hope that helps.
Do you want an answer for your specific case, or in general? In the case you described, there is nothing wrong with using an Abstract class. It doesn't make sense use an interface when all of the clients would need to implement the exact same code for Move() and Stop().
Don't believe all you read
Many times, inheritance is not bad, in fact, for data-hiding, it may be a good idea.
Basically, only use the policy of "interfaces only" when you're making a very small tree of classes, otherwise, I promise it will be a pain. Suppose you have a Person "class" (has eat() and sleep), and there are two subclasses, Mathematician (has doProblem() ) and Engineer ( buildSomething() ), then go with interfaces. If you need something like a Car class and then 56 bazillion types of cars, then go with inheritance.
IMHO.
I think, that Interfaces sometime also evil. They could be as avoidance of multiple inheritance.
But if we compare interface with abstract class, then abstract class is always more than interface. Interface is always some aspect of the class -- some viewpoint, and not whole as a class.
So I don't think you should avoid inheritance and use iterfaces everywhere -- there should be balance.

Doubt in using the interface?

Whenever i hear about interfaces i have the following doubt.
i have the following interface
interface Imammals
{
walk();
eat();
run();
}
and i have two classes Human and Cat that implements this interface.
Anyway, the functionality of the methods are going to be different in both the Classes.
For Eg: walk(), the functionality differs as cat uses four legs and human uses two legs
Then, Why do i need to have a common interface which ONLY declares these methods? Is my design here faulty?
If the functionality of the methods are going to be same in both the classes, i could go for a class based inheritance where the parent implements the complete functionality and the child inherits and uses the parent class methods.
But here the interfaces help us just to consolidate the methods declarations or is there anything more inside?
EDIT: walking(), eating(), running() was changed to walk(), eat(), run() and mammals was changes to Imammals.
In your scenario, either type-inheritance or interface-implementation would work - but interface based abstraction allows types outside of your existing type model to provide the functionality. It could be a mock object, or it could be some kind of super killer robot, that can walk run and eat but isn't really a mammal (so having it inherit from a Mammal class could be confusing or just impossible).
In particular, interfaces allow us to express this relationship neatly, while avoiding the subtle points from C# having single (type-)inheritance.
Using the interface you can have the following:
public void walkMyAnimal(Animal animal) {
animal.walk();
}
without the need to know what animal exactly is passed.
Interface allows you to define behavior for inheriting classes so if you have Donkey in future then you simply implement this interface and be sure that you donkey will walk,run and eat.
Also you can use composition instead of concrete implementation if some of your objects have common behaviour.
Read a bit about Strategy pattern I think that will help.
One big advantage of interfaces is that even in languages like Java and C# where multiple inheritance is not allowed, a class can take on more than one interface. Something can be both Closable, for instance, and a List, but could not inherit from both (hypothetical) abstract base classes AbstractClosable and AbstractList.
It is also suitable for cases where you are writing a library or a plugin interface and want to provide a way for your code to use objects provided by library users or plugin writers, but you don't want (nor should you) any say in the implementation. Think of the Listener interfaces in Java, for instance. Without those, there would be no possibility of an event model, since Java doens't support callbacks.
In general, interfaces are good for cases where you want objects that have particular functionality, but the way that functionality is implemented can vary widely, and might not be the only thing a class does.
The reason you want an interface is to be able to treat them all alike when commanding them.
Whoever calls walking() (which is a rather odd name btw, it should probably be walk()) is just interested in telling your animal to do just that. The actual implementation will vary but that is not something the caller would care about.
Well, sometimes you'd want to be able to do something to "anything capable of running" without necessarily knowing at design time whether you're talking about a human or a cat or whatever. For instance, imagine a function mammal raceWinner(mammal m1, mammal m2){...}
to calculate which mammal would win in a race. To determine who wins, perhaps the function needs to call m1.running() and m2.running(). Of course, the mammals we pass in will really be cats or humans or whatever, and this class supplies the actual implementation of running(). But all raceWinner needs to know is that they have a running() method with the expected signature.
If we only defined running() on cat and human, we couldn't call m1.running() (because the compiler is not guaranteed that m1 has a running() method, as it only knows it's a m1 implements mammal). So instead we'd have to implement a raceWinner(human m1, cat m2) and likewise for two humans, two cats, or any other pair of mammals we had in mind, leading to a lot more work on our part.
An interface provides a contract. It doesn't provide an implementation. It's good practice to interface out your classes.
Of course, walking(), eating() will have different implementation in different animals. But they all walk, run, etc. That is all the interface is saying.
You could model this using inheritance, which would allow you to give default implementations for some or all of the methods. However, interfaces are really useful for declaring a set of features that apply to many unrelated types.
To continue your example, you could imagine a type Alien, which would probably have the same methods, but would not fit in your inheritance hierarchy.
The purpose of interfaces is to tell you what a class does, not how it does it.
This is especially important for accepting things that work differently -- each printer we attach to the PC works differently, so does each scanner, so does each external drive. If all programs needed to care about how each of them worked, you would need to recompile, say, Microsoft Office, for every model of printer that comes out.
One way to develop interfaces is to define an interface and a relative class which implements te interface a common reasonable way. Having both interface and class, you could use the interface in the case the class alreay derives from another class, otherwise a class could derived derivctly to the interface implementation.
It's not always possible, but it solves many problem.
Having a common interface is used to use different object using only the interface (collecting them to a generic list, for example).
There isn't much difference between an entirely abstract class and an interface if you only have one base type. Interfaces can't have any implementation code, but abstract classes can. In this case, abstract classes can be more flexible.
Where interfaces are really useful is that you can assign multiple interfaces to a single implementation, but you can only assign one base class.
for instance, you could have:
class Cat : IMammal, IFourLeggedAnimal
{
}
class Human: IMammal, ITwoLeggedAnimal
{
}
Now you can treat both of them as Mammals, with a "walk()" method, or you can treat them as Four or two legged animals (not necessarily mammals).
What is really useful with an interface like mammal is that you can treat an array of objects (Humans and Cats) as of being of the same type when you want them to walk, eat or run.
For instance if you ware creating a game where you have a number (objects would be created dynamically, but just for example lets say 10 cats and 1 human) of mammals on the screen (saved in a collection), and just wanted them to walk on every turn, you could simply do:
foreach(mammals m in MamalsArrayList){
{
m.walking();
}
note: I suggest you follow naming conventions and name your interfaces with "I" in front of them, so your example should be named IMammals.
without having to know weather any particular m is either a cat or a human.
Interfaces are hard to show on any particular snippet - but when you really need one you can see how useful they can be.
Of course they have other uses to (that are mentioned in other answers), I just focused on your example.
There are two issues here that are often confused. Inherited behaviour allows different 'commands' to be responded to in the same way e.g Man.walk() === Woman.walk(). Polymorphic behaviour allows the same 'command' to be responded to in different ways e.g. Animal.move() for one object may be different for Animal.move() for another, the bird will choose to fly while the slug will slide.
Now, I would argue the second of these is good while the first is not. Why? Because in OOP we should be encapsulating functionality into objects, which in turn promotes code reuse and all the other nicenesses of OOP. So rather than inheriting behaviour we should delegate it out to a shared object. If you know patterns then this is what State and Strategy are doing.
The problem lies in the fact that normally when you inherit , you get both of these behaviours mixed together. I suggest that this is more trouble than its worth and we should only be using interfaces, though sometimes we do have to make do with whatever the framework provides.
In your specific example Mammal is probably a bad interface name because it doesn't really tell me what it does and it has the potential to blowout to thousands of methods. It's better to divide interfaces into very specific cases. If you were modelling animals you might have a Moveable interface with one method, move(), to which each animal could respond by walking, running, flying, or crawling as appropriate.

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();
}

Why should you prevent a class from being subclassed?

What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class)
Right now I can't think of any.
Because writing classes to be substitutably extended is damn hard and requires you to make accurate predictions of how future users will want to extend what you've written.
Sealing your class forces them to use composition, which is much more robust.
How about if you are not sure about the interface yet and don't want any other code depending on the present interface? [That's off the top of my head, but I'd be interested in other reasons as well!]
Edit:
A bit of googling gave the following:
http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx
Quoting:
There are three reasons why a sealed class is better than an unsealed class:
Versioning: When a class is originally sealed, it can change to unsealed in the future without breaking compatibility. (…)
Performance: (…) if the JIT compiler sees a call to a virtual method using a sealed types, the JIT compiler can produce more efficient code by calling the method non-virtually.(…)
Security and Predictability: A class must protect its own state and not allow itself to ever become corrupted. When a class is unsealed, a derived class can access and manipulate the base class’s state if any data fields or methods that internally manipulate fields are accessible and not private.(…)
I want to give you this message from "Code Complete":
Inheritance - subclasses - tends to
work against the primary technical
imperative you have as a programmer,
which is to manage complexity.For the sake of controlling complexity, you should maintain a heavy bias against inheritance.
The only legitimate use of inheritance is to define a particular case of a base class like, for example, when inherit from Shape to derive Circle. To check this look at the relation in opposite direction: is a Shape a generalization of Circle? If the answer is yes then it is ok to use inheritance.
So if you have a class for which there can not be any particular cases that specialize its behavior it should be sealed.
Also due to LSP (Liskov Substitution Principle) one can use derived class where base class is expected and this is actually imposes the greatest impact from use of inheritance: code using base class may be given an inherited class and it still has to work as expected. In order to protect external code when there is no obvious need for subclasses you seal the class and its clients can rely that its behavior will not be changed. Otherwise external code needs to be explicitly designed to expect possible changes in behavior in subclasses.
A more concrete example would be Singleton pattern. You need to seal singleton to ensure one can not break the "singletonness".
This may not apply to your code, but a lot of classes within the .NET framework are sealed purposely so that no one tries to create a sub-class.
There are certain situations where the internals are complex and require certain things to be controlled very specifically so the designer decided no one should inherit the class so that no one accidentally breaks functionality by using something in the wrong way.
#jjnguy
Another user may want to re-use your code by sub-classing your class. I don't see a reason to stop this.
If they want to use the functionality of my class they can achieve that with containment, and they will have much less brittle code as a result.
Composition seems to be often overlooked; all too often people want to jump on the inheritance bandwagon. They should not! Substitutability is difficult. Default to composition; you'll thank me in the long run.
I am in agreement with jjnguy... I think the reasons to seal a class are few and far between. Quite the contrary, I have been in the situation more than once where I want to extend a class, but couldn't because it was sealed.
As a perfect example, I was recently creating a small package (Java, not C#, but same principles) to wrap functionality around the memcached tool. I wanted an interface so in tests I could mock away the memcached client API I was using, and also so we could switch clients if the need arose (there are 2 clients listed on the memcached homepage). Additionally, I wanted to have the opportunity to replace the functionality altogether if the need or desire arose (such as if the memcached servers are down for some reason, we could potentially hot swap with a local cache implementation instead).
I exposed a minimal interface to interact with the client API, and it would have been awesome to extend the client API class and then just add an implements clause with my new interface. The methods that I had in the interface that matched the actual interface would then need no further details and so I wouldn't have to explicitly implement them. However, the class was sealed, so I had to instead proxy calls to an internal reference to this class. The result: more work and a lot more code for no real good reason.
That said, I think there are potential times when you might want to make a class sealed... and the best thing I can think of is an API that you will invoke directly, but allow clients to implement. For example, a game where you can program against the game... if your classes were not sealed, then the players who are adding features could potentially exploit the API to their advantage. This is a very narrow case though, and I think any time you have full control over the codebase, there really is little if any reason to make a class sealed.
This is one reason I really like the Ruby programming language... even the core classes are open, not just to extend but to ADD AND CHANGE functionality dynamically, TO THE CLASS ITSELF! It's called monkeypatching and can be a nightmare if abused, but it's damn fun to play with!
From an object-oriented perspective, sealing a class clearly documents the author's intent without the need for comments. When I seal a class I am trying to say that this class was designed to encapsulate some specific piece of knowledge or some specific service. It was not meant to be enhanced or subclassed further.
This goes well with the Template Method design pattern. I have an interface that says "I perform this service." I then have a class that implements that interface. But, what if performing that service relies on context that the base class doesn't know about (and shouldn't know about)? What happens is that the base class provides virtual methods, which are either protected or private, and these virtual methods are the hooks for subclasses to provide the piece of information or action that the base class does not know and cannot know. Meanwhile, the base class can contain code that is common for all the child classes. These subclasses would be sealed because they are meant to accomplish that one and only one concrete implementation of the service.
Can you make the argument that these subclasses should be further subclassed to enhance them? I would say no because if that subclass couldn't get the job done in the first place then it should never have derived from the base class. If you don't like it then you have the original interface, go write your own implementation class.
Sealing these subclasses also discourages deep levels of inheritence, which works well for GUI frameworks but works poorly for business logic layers.
Because you always want to be handed a reference to the class and not to a derived one for various reasons:
i. invariants that you have in some other part of your code
ii. security
etc
Also, because it's a safe bet with regards to backward compatibility - you'll never be able to close that class for inheritance if it's release unsealed.
Or maybe you didn't have enough time to test the interface that the class exposes to be sure that you can allow others to inherit from it.
Or maybe there's no point (that you see now) in having a subclass.
Or you don't want bug reports when people try to subclass and don't manage to get all the nitty-gritty details - cut support costs.
Sometimes your class interface just isn't meant to be inheirited. The public interface just isn't virtual and while someone could override the functionality that's in place it would just be wrong. Yes in general they shouldn't override the public interface, but you can insure that they don't by making the class non-inheritable.
The example I can think of right now are customized contained classes with deep clones in .Net. If you inherit from them you lose the deep clone ability.[I'm kind of fuzzy on this example, it's been a while since I worked with IClonable] If you have a true singelton class, you probably don't want inherited forms of it around, and a data persistence layer is not normally place you want a lot of inheritance.
Not everything that's important in a class is asserted easily in code. There can be semantics and relationships present that are easily broken by inheriting and overriding methods. Overriding one method at a time is an easy way to do this. You design a class/object as a single meaningful entity and then someone comes along and thinks if a method or two were 'better' it would do no harm. That may or may not be true. Maybe you can correctly separate all methods between private and not private or virtual and not virtual but that still may not be enough. Demanding inheritance of all classes also puts a huge additional burden on the original developer to foresee all the ways an inheriting class could screw things up.
I don't know of a perfect solution. I'm sympathetic to preventing inheritance but that's also a problem because it hinders unit testing.
I exposed a minimal interface to interact with the client API, and it would have been awesome to extend the client API class and then just add an implements clause with my new interface. The methods that I had in the interface that matched the actual interface would then need no further details and so I wouldn't have to explicitly implement them. However, the class was sealed, so I had to instead proxy calls to an internal reference to this class. The result: more work and a lot more code for no real good reason.
Well, there is a reason: your code is now somewhat insulated from changes to the memcached interface.
Performance: (…) if the JIT compiler sees a call to a virtual method using a sealed types, the JIT compiler can produce more efficient code by calling the method non-virtually.(…)
That's a great reason indeed. Thus, for performance-critical classes, sealed and friends make sense.
All the other reasons I've seen mentioned so far boil down to "nobody touches my class!". If you're worried someone might misunderstand its internals, you did a poor job documenting it. You can't possibly know that there's nothing useful to add to your class, or that you already know every imaginable use case for it. Even if you're right and the other developer shouldn't have used your class to solve their problem, using a keyword isn't a great way of preventing such a mistake. Documentation is. If they ignore the documentation, their loss.
Most of answers (when abstracted) state that sealed/finalized classes are tool to protect other programmers against potential mistakes. There is a blurry line between meaningful protection and pointless restriction. But as long as programmer is the one who is expected to understand the program, I see no hardly any reasons to restrict him from reusing parts of a class. Most of you talk about classes. But it's all about objects!
In his first post, DrPizza claims that designing inheritable class means anticipating possible extensions. Do I get it right that you think that class should be inheritable only if it's likely to be extended well? Looks as if you were used to design software from the most abstract classes. Allow me a brief explanation of how do I think when designing:
Starting from the very concrete objects, I find characteristics and [thus] functionality that they have in common and I abstract it to superclass of those particular objects. This is a way to reduce code duplicity.
Unless developing some specific product such as a framework, I should care about my code, not others (virtual) code. The fact that others might find it useful to reuse my code is a nice bonus, not my primary goal. If they decide to do so, it's their responsibility to ensure validity of extensions. This applies team-wide. Up-front design is crucial to productivity.
Getting back to my idea: Your objects should primarily serve your purposes, not some possible shoulda/woulda/coulda functionality of their subtypes. Your goal is to solve given problem. Object oriented languages uses fact that many problems (or more likely their subproblems) are similar and therefore existing code can be used to accelerate further development.
Sealing a class forces people who could possibly take advantage of existing code WITHOUT ACTUALLY MODIFYING YOUR PRODUCT to reinvent the wheel. (This is a crucial idea of my thesis: Inheriting a class doesn't modify it! Which seems quite pedestrian and obvious, but it's being commonly ignored).
People are often scared that their "open" classes will be twisted to something that can not substitute its ascendants. So what? Why should you care? No tool can prevent bad programmer from creating bad software!
I'm not trying to denote inheritable classes as the ultimately correct way of designing, consider this more like an explanation of my inclination to inheritable classes. That's the beauty of programming - virtually infinite set of correct solutions, each with its own cons and pros. Your comments and arguments are welcome.
And finally, my answer to the original question: I'd finalize a class to let others know that I consider the class a leaf of the hierarchical class tree and I see absolutely no possibility that it could become a parent node. (And if anyone thinks that it actually could, then either I was wrong or they don't get me).