Are there established alternatives to ISomething / ISomethingable for interfaces? - naming-conventions

The .NET standard of prefixing an interface name with an I seems to be becoming widespread and isn't just limited to .NET any more. I have come across a lot of Java code that uses this convention (so it wouldn't surprise me if Java used it before C# did). Also Flex uses it, and so on. The placing of an I at the start of the name smacks of Hungarian notation though and so I'm uncomfortable with using it.
So the question is, is there an alternative way of denoting that Something is an interface, rather than a class and is there any need to denote it like this anyway. Or is it a case its become a standard and so I should just accept it and stop trying to stir up "religious wars" by suggesting it be done differently?

From the Framework Design Guidelines book:
Interfaces representing roots of a hierarchy (e.g. IList) should also use nouns or noun phrases. Interfaces representing capabilities should use adjectives and adjective phrases (e.g. IComparable, IFormattable).
Also, from the annotations on interface naming:
KRZYSZTOF CWALINA: One of the few
prefixes used is “I” for interfaces
(as in ICollection), but that is for
historical reasons. In retrospect, I
think it would have been better to use
regular type names. In a majority of
the cases developers don’t care that
something is an interface and not an
abstract class, for example.
BRAD ABRAMS: On the other hand, the “I” prefix on interfaces is a clear
recognition of the influence of COM
(and Java) on the .NET Framework. COM
popularized, even institutionalized,
the notation that interfaces begin
with “I.” Although we discussed
diverging from this historic pattern
we decided to carry forward the
pattern as so many of our users were
already familiar with COM.
JEFFREY RICHTER: Personally, I like the
“I” prefix and I wish we had more
stuff like this. Little one-character
prefixes go a long way toward keeping
code terse and yet descriptive. As I
said earlier, I use prefixes for my
private type fields because I find
this very useful.
BRENT RECTOR Note:
this is really another application of
Hungarian notation (though one without
the disadvantages of the notation's
use in variable names).
It has very much become a widely adopted standard, and while it is a form of Hungarian, as Brent states, it doesn't suffer from the disadvantages of using Hungarian notation in variable names.

I would just accept it, to be honest. I know what you mean about being a bit like Hungarian notation (or at least abuse of the same) but I think it gives sufficient value to be worth doing in this case.
With dependency injection being in vogue, often I find I end up with an interface and a single production implementation. It's handy to make them easily distinguishable just with the I prefix.
One little data point: I work with both Java and C# a fair amount, and I regularly find myself having to check which types in Java are actually interfaces, particularly around the collection framework. .NET just makes this simple. Maybe it doesn't bother other people, but it bothers me.
+1 for IFoo from me.

As a .NET programmer (for the most part), I actually prefer the Java convention of dropping the I here, for a simple reason: Often, small redesigns require the change from an interface into an abstract base class or vice versa. If you have to change the name, this might require a lot of unnecessary refactoring.
On the other hand, usage for the client should be transparent so they shouldn't care for this type hint. Furthermore, the “able” suffix in `Thingable” should be enough of a hint. It works well enough in Java.
/EDIT: I'd like to point out that the above reasoning had prompted me to drop the I prefix for private projects. However, upon checking one of them against the FxCop rule set, I promptly reverted to the usage of I. Consistency wins here, even though a foolish consistency is the hobgoblin of little minds.

Its all about style and readability. Prefixing Interfaces with "I" is merely a naming convention and style guideline that has caught on. The compilers themselves couldn't care less.

My main assumption is that the most important thing is to maintain readability in domain part of the implementation. Therefore:
If you have one behaviour and one possible implementation, then just don't create an interface:
public class StackOverflowAnswerGenerator { }
If you have one behaviour and many possible implementations, then there is no problem and you can just drop the "I", and have:
public interface StackOverflowAnswerGenerator {}
public class StupidStackOverflowAnswerGenerator : StackOverflowAnswerGenerator {}
public class RandomStackOverflowAnswerGenerator : StackOverflowAnswerGenerator {}
public class GoogleSearchStackoverflowAnswerGenerator : StackOverflowAnswerGenerator {}
//...
The real problem comes when you have one behaviour and one possible implementation but you need an interface to describe its behaviour (for example for convenient testing, because of convention in your project, using some library/framework which enforces this, ...). Possible solutions, other from prefixing the interface are:
a) Prefix or suffix the implementation (as stated in some other answers in this topic)
b) Use a different namespace for interface:
namespace StackOverflowAnswerMachine.Interfaces
{
public interface StackOverflowAnswerGenerator {}
}
namespace StackOverflowAnswerMachine
{
public class StackOverflowAnswerGenerator : Interfaces.StackOverflowAnswerGenerator
{}
}
c) Use a different namespace for implementation:
namespace StackOverflowAnswerMachine
{
public interface StackOverflowAnswerGenerator {}
}
namespace StackOverflowAnswerMachine.Implementations
{
public class StackOverflowAnswerGenerator : StackOverflowAnswerMachine.StackOverflowAnswerGenerator
{}
}
Even though I think the last possibility is the cleanest, its one drawback is that even though using StackOverflowAnswerMachine; gives you access to all domain objects you must prefix all domain interfaces not to be confused with their implementations. That may feel like something not very convenient but in clean design usually a class doesn't use many other domain objects, and mostly you need to use the prefix only in field declaration and constructor parameter list. So, that is my current recommendation.
The client of domain functionality shouldn't need to know whether they're using an interface, an abstract class or a concrete class. If they need to know this, then there is some serious problem in such a project, because it has domain logic and infrastructural concerns mixed on the same abstraction layer. Therefore I recommend "a" or "c" solutions.

The coding standard for Symbian has interfaces (pure abstract C++ classes) denoted with an M rather than an I.
Otherwise, the only other way I have seen of denoting interfaces is through context.

For .NET, Microsoft's Framework Design Guidelines book absolutely recommends it, and yes, it is very much standard. I have never seen it done otherwise, and to create a new convention would only serve to confuse people.
I should add that I dislike Hungarian notation too, but this and the case of prefixing class variables with an underscore are good exceptions to me, because they make code so much more readable.

I've always thought this naming convention is a bit of a dinosaur. Nowadays IDEs are powerful enough to tell us that something is an interface. Adding that I makes the code harder to read so if you really want to have a naming convention that separates interfaces from classes I would append Impl to the name of the implementing class.
public class CustomerImpl implements Customer

You asked for an alternative, so here is one I have encountered:
Use no prefix on the interface class, but use a c or C prefix on the corresponding concrete classes. Most of your code will generally reference the interface, so why pollute it with the prefix and not the generally much less used concrete type.
This approach does introduce one inconsistency in that some concrete types will be prefixed (the ones with matching interfaces) and others will not. This may be useful since it reminds developers that an interface exists and its use should be preferred over the concrete type.
To be honest, I use the prefix on the interface, but I think it is more because I have become so accustomed and comfortable with to it.

Related

Should I be using inheritance?

This is more of a subjective question, so I'm going to preemptively mark it as community wiki.
Basically, I've found that in most of my code, there are many classes, many of which use each other, but few of which are directly related to each other. I look back at my college days, and think of the traditional class Cat : Animal type examples, where you have huge inheritance trees, but I see none of this in my code. My class diagrams look like giant spiderwebs, not like nice pretty trees.
I feel I've done a good job of separating information logically, and recently I've done a good job of isolating dependencies between classes via DI/IoC techniques, but I'm worried I might be missing something. I do tend to clump behavior in interfaces, but I simply don't subclass.
I can easily understand subclassing in terms of the traditional examples such as class Dog : Animal or class Employee : Person, but I simply don't have anything that obvious I'm dealing with. And things are rarely as clear-cut as class Label : Control. But when it comes to actually modeling real entities in my code as a hierarchy, I have no clue where to begin.
So, I guess my questions boil down to this:
Is it ok to simply not subclass or inherit? Should I be concerned at all?
What are some strategies you have to determine objects that could benefit from inheritance?
Is it acceptable to always inherit based on behavior (interfaces) rather than the actual type?
Inheritance should always represent an "is-a" relationship. You should be able to say "A is a B" if A derives from B. If not, prefer composition. It's perfectly fine to not subclass when it is not necessary.
For example, saying that FileOpenDialog "is-a" Window makes sense, but saying that an Engine "is-a" Car is nonsense. In that case, an instance of Engine inside a Car instance is more appropriate (It can be said that Car "is-implemented-in-terms-of" Engine).
For a good discussion of inheritance, see Part 1 and Part 2 of "Uses and Abuses of Inheritance" on gotw.ca.
As long as you do not miss the clear cut 'is a' relationships, it's ok and in fact, it's best not to inherit, but to use composition.
is-a is the litmus test. if (Is X a Y?) then class X : Y { } else class X { Y myY; } or class Y { X myX; }
Using interfaces, that is, inheriting behavior, is a very neat way to structure the code via adding only the needed behavior and no other. The tricky part is defining those interfaces well.
No technology or pattern should be used for its own sake. You obviously work in a domain where classes tend to not benefit from inheritance, so you shouldn't use inheritance.
You've used DI to keep things neat and clean. You separated the concerns of your classes. Those are all good things. Don't try and force inheritance if you don't really need it.
An interesting follow-up to this question would be: Which programming domains do tend to make good use of inheritance? (UI and db frameworks have already been mentioned and are great examples. Any others?)
I also hate the Dog -> Mammal -> Animal examples, precisely because they do not occur in real life.
I use very little subclassing, because it tightly couples the subclass to the superclass and makes your code really hard to read. Sometimes implementation inheritance is useful (e.g. PostgreSQLDatabaseImpl and MySQLDatabaseImpl extend AbstractSQLDatabase), but most of the time it just makes a mess of things. Most of the time I see subclasses the concept has been misused and either interfaces or a property should be used.
Interfaces, however, are great and you should use those.
Generally, favour composition over inheritance. Inheritance tends to break encapsulation. e.g. If a class depends on a method of a super class and the super class changes the implementation of that method in some release, the subclass may break.
At times when you are designing a framework, you will have to design classes to be inherited. If you want to use inheritance, you will have to document and design for it carefully. e.g. Not calling any instance methods (that could be overridden by your subclasses) in the constructor. Also if its a genuine 'is-a' relationship, inheritance is useful but is more robust if used within a package.
See Effective Java (Item 14, and 15). It gives a great argument for why you should favour composition over inheritance. It talks about inheritance and encapsulation in general (with java examples). So its a good resource even if you are not using java.
So to answer your 3 questions:
Is it ok to simply not subclass or inherit? Should I be concerned at all?
Ans: Ask yourself the question is it a truly "is-a" relationship? Is decoration possible? Go for decoration
// A collection decorator that is-a collection with
public class MyCustomCollection implements java.util.Collection {
private Collection delegate;
// decorate methods with custom code
}
What are some strategies you have to determine objects that could benefit from inheritance?
Ans: Usually when you are writing a framework, you may want to provide certain interfaces and "base" classes specifically designed for inheritance.
Is it acceptable to always inherit based on behavior (interfaces) rather than the actual type?
Ans: Mostly yes, but you'd be better off if the super class is designed for inheritance and/or under your control. Or else go for composition.
IMHO, you should never do #3, unless you're building an abstract base class specifically for that purpose, and its name makes it clear what its purpose is:
class DataProviderBase {...}
class SqlDataProvider : DataProviderBase {...}
class DB2DataProvider : DataProviderBase {...}
class AccountDataProvider : SqlDataProvider {...}
class OrderDataProvider : SqlDataProvider {...}
class ShippingDataProvider : DB2DataProvider {...}
etc.
Also following this type of model, sometimes if you provide an interface (IDataProvider) it's good to also provide a base class (DataProviderBase) that future consumers can use to conveniently access logic that's common to all/most DataProviders in your application model.
As a general rule, though, I only use inheritance if I have a true "is-a" relationship, or if it will improve the overall design for me to create an "is-a" relationship (provider model, for instance.)
Where you have shared functionality, programming to the interface is more important than inheritance.
Essentially, inheritance is more about relating objects together.
Most of the time we are concerned with what an object can DO, as opposed to what it is.
class Product
class Article
class NewsItem
Are the NewsItem and Article both Content items? Perhaps, and you may find it useful to be able to have a list of content which contains both Article items and NewsItem items.
However, it's probably more likely you'll have them implement similar interfaces. For example, IRssFeedable could be an interface that they both implement. In fact, Product could also implement this interface.
Then they can all be thrown to an RSS Feed easily to provide lists of things on your web page. This is a great example when the interface is important whereas the inheritance model is perhaps less useful.
Inheritance is all about identifying the nature of Objects
Interfaces are all about identifying what Objects can DO.
My class hierarchies tend to be fairly flat as well, with interfaces and composition providing the necessary coupling. Inheritance seems to pop up mostly when I'm storing collections of things, where the different kinds of things will have data/properties in common. Inheritance often feels more natural to me when there is common data, whereas interfaces are a very natural way to express common behavior.
The answer to each of your 3 questions is "it depends". Ultimately it will all depend on your domain and what your program does with it. A lot of times, I find the design patterns I choose to use actually help with finding points where inheritance works well.
For example, consider a 'transformer' used to massage data into a desired form. If you get 3 data sources as CSV files, and want to put them into three different object models (and maybe persist them into a database), you could create a 'csv transformer' base and then override some methods when you inherit from it in order to handle the different specific objects.
'Casting' the development process into the pattern language will help you find objects/methods that behave similarly and help in reducing redundant code (maybe through inheritance, maybe through the use of shared libraries - whichever suits the situation best).
Also, if you keep your layers separate (business, data, presentation, etc.), your class diagram will be simpler, and you could then 'visualize' those objects that aught to be inherited.
I wouldn't get too worried about how your class diagram looks, things are rarely like the classroom...
Rather ask yourself two questions:
Does your code work?
Is it extremely time consuming to maintain? Does a change sometimes require changing the 'same' code in many places?
If the answer to (2) is yes, you might want to look at how you have structured your code to see if there is a more sensible fashion, but always bearing in mind that at the end of the day, you need to be able to answer yes to question (1)... Pretty code that doesn't work is of no use to anybody, and hard to explain to the management.
IMHO, the primary reason to use inheritance is to allow code which was written to operate upon a base-class object to operate upon a derived-class object instead.

Using "Base" in a Class Name

Is it acceptable to use the word 'Base' in a class name which is a the bottom of the inheritance tree?
I have always found this a bit of a cop-out, just wondering if anyone agrees with me.
For example, if I am refactoring certain elements from MyClassA and MyClassB into a common base class, I'd be tempted to create a MyBaseClass from which the two inherit.
But what happens if I ever need to refactor MyBaseClass? MyBaseBaseClass? Now that's just silly.
I know that Rocky Lhotka doesn't mind with his CSLA framework, but I'm always uneasy about 'definites' in programming.
Thoughts?
Let me clarify why I'm even worrying about this.
I have two namespaces - MySpecificNamespace and MyCommonNamespace. MyNamespace uses MyCommonNamespace, as you might expect.
Now, I like to make maximum use of Namespaces wherever possible to describe the context of the problem, and avoid adding the context to the class name. So, for example, consider that I have a class in MyNamespace which descends from one in MyCommonNamespace.
Option A
I could call this
MySpecificClass: MyClass
{
}
But then I'm adding 'Specific' (the context) to the name - which is redundant as it's already in MySpecificNamespace.
Option B
MyClass: MyCommonNamespace.MyClass
{
}
You can see how we could get confused here, right?
Option C
The one I think is fishy:
MyClass: MyBaseClass
{
}
I tend to add a Base suffix to the name of the base class only if it exists from technical perspective (to share some code), and doesn't really constitute any usable class on its own (so all of these classes are abstract). These are quite rare cases though, and should be avoided just as Helper classes.
"All your BaseClass are belong to us."
I side with a definitive no, with a single exception. If you are writing an app to manage military installations or baseball stadiums, go for it.
I side with "no" for exactly the refactoring reason you've cited.
A class should be named after what it logically represents, and nothing but the Object class is really really Base. Metaphysics ftw :)
re: Option B, there is nothing confusing about
namespace MySpecificNamespace
{
MyClass: MyCommonNamespace.MyClass
{
}
}
Classes that have the same name as their parent classes bug me to no end. In Java java.sql.Date extends java.util.Date. This is very annoying because you have to specify the exact class you want to import or else specify the classname fully (including package/namespace).
Personally I prefer to name things as they are; if a Base or Abstract class exists only to provide a partial implementation of something, and doesn't represent the interface for that thing, it is often acceptable to put the word Abstract or Base in its name. However, if that class represents the interface as well, then you should just name it after what it does.
For example, in Java, we have the Connection interface (for DB connections). It's just called Connection, not IConnection. You use it like this:
Connection con = getConnectionFromSomewhere();
If you are making a JDBC driver and need to implement connection, you could have a ConnectionBase or AbstractConnection which is the lower layer of the implementation detail of your particular Connection. You might have
abstract class AbstractConnection implements Connection
class OracleConnection extends AbstractConnection
or something like that. The clients of your code, however, never see AbstractConnection nor do they see OracleConnection, they only see Connection.
So, in general, classes that are meant to be generally useful should be named after what they represent/do, whereas classes that are helpers for code maintenance/organization can be named after what they are.
*ps I hate naming Interfaces with I. Do people name all their classes with C? It's 2009! your IDE can tell you what type of object that is, in the odd case when it even matters if it's an interface or a class.
I think it's worth wiki-fying this question.
FWIW, I agree. I usually try to find a more "generic" term for my base classes. So if I have a "Customer" class and need to introduce a new base class for it, I'd go with "Contact" or something rather than "CustomerBase".
I too would suggest No, but not cast in stone...
Following OO mantra, your naming system should best represent the underlying objects that the code is supposed to be encapsulating. There should really be no 'meta language', related to the actual syntactical makeup of the programming language of choice in there.
That said, if your object is truly abstract and you really don't see it changing anytime soon, there is an argument that adding 'Base' helps with general readability.
As with most things, there's no blanket right and wrong answer - it depends on the overall layout of your codebase, what this specific code is supposed to be representing and the in-house style that you have. Just try to be consistent.
Is base used anywhere else?
In Java I tend to provide a base implementation of an interface Foo in an abstract class FooBase. I think that is perfectly ok, and makes the connection to the interface very clear and regular.
Without the interface I would call the abstract base class Foo.
I also side with the no camp...place a Base in there today and in 6 months someone will whack a MyDerivedClass class in you code base while you're not looking.
"Abstract" prefix maybe?
I usually go with IFoo for the interface and AbstractFoo for the skeletal implementation, which is a mix of .NET and Java conventions.
I think it should probably be avoided where possible in favour of an identifier that actually describes what it is!
This question is difficult to answer because it's abstract. I might, for example, consider calling the base of MyClassA and MyClassB, "MyClass".
I agree, AbstractFoo is a decent solution. I try to pick names that don't need additional adjectives. I would shy away from using Base.
It seems like any principled answer will end up being no... However, comma, when I'm looking at code I'm not particularly familiar with, which happens a lot in python (where the source code is sometimes the only dependable documentation), I find it really helpful when a class has Base in it. Python is different from other OO languages where the class is defined with an "abstract" or "interface" specifier though. For naming, I like to ask myself "if I have never seen this code before, which way would make it easier for me to understand this code?" (Then, depending on how lazy I'm feeling, I name it accordingly).

Is there a best way to handle naming fads?

In the last year and a bit of working on my team's code base I have noticed a steady progression of naming conventions.
For example, there are a lot of classes that are named to express that they are a class that helps you do something.
Here's the ones I've spotted:
MyClassUtil
MyClassFactory
MyClassHelper
MyClassManager
MyClassService
It just seems to me that over time people come up with naming conventions for relatively the same thing and so instead of having everything named in a consistent manner you wind up with a code base that has a bit of every convention. All the new stuff is named based on the latest fad naming convention and so you can pretty much tell the age of a bit of code by what convention was in fashion at the time.
What is the best way to deal with this tendency? Is it really a problem? As these naming fads come into vogue, should one use the latest fad? Should one rename all existing items with the new naming convention? Or should one just accept the variety as something that is inescapable?
They don't seem like fads... all these names hint at the purpose of the class, and those purposes are different. With programming, it's all in the name, and they should be chosen very carefully. The variety doesn't need to be escaped. The names vary because the purposes of the classes vary.
MyClassUtil
-Some utilities for working with MyClass that it didn't come with. Maybe MyClass belongs to a library you're using, but you often use some higher level functions with it and you need somewhere to put them.
MyClassFactory
-Creates instances of MyClass in an abstracted way. This allows you to write code that needs MyClass instances. It can get those new instances from a MyClassFactory. This would allow the Factory to modified in future to serve up different specific implementations of MyClass. Maybe under unit testing, the Factory just serves up dummy/mock MyClasses. This means a class that uses the factory can be tested without needing to change it, just change the factory, and voilà you can isolate the class being tested.
MyClassHelper
-Ok, I may agree, perhaps this can be more specific. It does something to help with MyClass, but what. Maybe this is a bit similar to MyClassUtil. But, probably MyClassUtil is general functions that work with MyClass, whereas the helper is initialized with a specific instance of MyClass and then can do operations on that one instance. You need a new helper for each MyClass you want to help.
MyClassManager
-Maybe this deals with a pool of MyClass instances and stores or orchestrates them. Eg. in a CommunicationsManager, the class would handle wiring together classes that handle talking to a port or connection like ethernet or serial, and a class that deals with the comms protocol being sent over it so it can transport packets, and a class that deals with the messages in those packets.
MyClassService
-A service can do things for you, like given a postcode convert it into a grid-reference. Usually a service can resolve to many specific things. With the postcode example, this class might be have implementations that can talk to different web sites to do the conversion.
All of the names of classes you've given above indicate to me a striking departure from object-oriented principles. There's no way of telling what "MyClassUtil" or "MyClassService" does. It could be anything. Class naming should be specific, and should relay clearly the actual function of the class. None of these do. The best way to deal with this tendency is to brush up on object oriented programming skills and name the classes accordingly.
Now, it could be that these examples point out the function, within the application architecture, that these classes represent, and your use of "MyClass" is simply a placeholder for something more definitive at runtime, in which case, I wouldn't view these as naming fads, but rather as descriptive indicators of the function of the class itself, with a loose hint of the application's underlying architecture.
If this is pervasive, the team needs to spend some time studying OO design: reading the source code to well-respected OO frameworks, books on design patterns or books such as Evans "Domain Driven Design".
"Util" and "Manager" are often symptoms of poor design - "code smells". So is "Helper" outside of special contexts (Rails apps) where it's well entrenched.
"Factory" and "Service" have precise technical meanings, you can check the code to see if it conforms to those design patterns.
The general remedy is to sit down with the team, and have an explicit discussion about what benefits you're expecting from these naming schemes, what makes sense and what doesn't, and then over the next few months apply refactoring techniques to phase out the names you've all decided are code smells.
Naming is important. It shouldn't be taken lightly, nor is it a subjective matter. True, there is often more than one correct answer to a given naming issue. However, there are seldom many answers consistent with previous choices, which is key.
Renaming the names to better ones and refactoring the code so that each class has a clear responsibility, is recommended. To know what kind of names to use, read Tim Ottinger's article about Meaningful Names.
When a class does only one thing, then giving it a descriptive name is usually easy. Words such as "manager" are vague and may indicate that the class is responsible for doing so many unrelated things, that no simple name is able to describe what the class does. If you can know what the class does just by looking at the name of the class, then the class has a good name.
I don't really see how Factory or Service fit in to a particular fad...
Factory is a design pattern and if the class really is a factory then it's a perfectly appropriate name.
If a class is a Windows service what's wrong with calling it service?
There isn't a problem unless you find that performing all the rename refactors is too costly even though you really want to do them.
Why not use a static analysis tool to help enforce a set of style and consistency rule?
If you're in the .NET world Microsoft provides a tool called StyleCop
In the classname examples you give does "MyClass" stand for an actual class name, so that you are really seeing names like "PersonnelRecordUtil" or "GraphNodeFactory"? MyClassFactory is a really bad actual name for a class.

Best practice for naming subclasses

I am often in a situation where I have a concept represented by an interface or class, and then I have a series of subclasses/subinterfaces which extend it.
For example:
A generic "DoiGraphNode"
A "DoiGraphNode" representing a resource
A "DoiGraphNode" representing a Java resource
A "DoiGraphNode" with an associated path, etc., etc.
I can think of three naming conventions, and would appreciate comments on how to choose.
Option 1: Always start with the name of the concept.
Thus: DoiGraphNode, DoiGraphNodeResource, DoiGraphNodeJavaResource, DoiGraphNodeWithPath, etc.
Pro: It is very clear what I am dealing with, it is easy to see all the options I have
Con: Not very natural? Everything looks the same?
Option 2: Put the special stuff in the beginning.
Thus: DoiGraphNode, ResourceDoiGraphNode, JavaResourceDoiGraphNode, PathBaseDoiGraphNode,
etc., etc.
Pro: It is very clear when I see it in the code
Con: Finding it could be difficult, especially if I don't remember the name, lack of visual consistency
Option 3: Put the special stuff and remove some of the redundant text
Thus: DoiGraphNode, ResourceNode, JavaResourceNode, GraphNodeWithPath
Pro: Not that much to write and read
Con: Looks like cr*p, very inconsistent, may conflict with other names
Name them for what they are.
If naming them is hard or ambiguous, it's often a sign that the Class is doing too much (Single Responsibility Principle).
To avoid naming conflicts, choose your namespaces appropriately.
Personnally, I'd use 3
Use whatever you like, it's a subjective thing. The important thing is to make clear what each class represents, and the names should be such that the inheritance relationships make sense. I don't really think it's all that important to encode the relationships in the names, though; that's what documentation is for (and if your names are appropriate for the objects, people should be able to make good guesses as to what inherits from what).
For what it's worth, I usually use option 3, and from my experience looking at other people's code option 2 is probably more prevalent than option 1.
You could find some guidance in a coding standards document, for example there is the IDesign document for C# here.
Personally, I prefer option 2. This is generally the way the .NET Framework names its objects. For instance look at attribute classes. They all end in Attribute (TestMethodAttribute). The same goes for EventHandlers: OnClickEventHandler is a recommended name for an event handler that handles the Click event.
I usually try to follow this in designing my own code and interfaces. Thus an IUnitWriter produces a StringUnitWriter and a DataTableUnitWriter. This way I always know what their base class is and it reads more naturally. Self-documenting code is the end-goal for all agile developers so it seems to work well for me!
I usually name similar to option 1, especially when the classes will be used polymophically.
My reasoning is that the most important bit of information is listed first.
(I.e. the fact that the subclass is basically what the ancestor is,
with (usually) extensions 'added').
I like this option also because when sorting lists of class names,
the related classes will be listed together.
I.e. I usually name the translation unit (file name) the same as
the class name so related class files will naturally be listed together.
Similarly this is useful with incremental search.
Although I tended to use option 2 earlier in my programming career, I avoid it now because as you say it is 'inconsistant' and do not seem very orthogonal.
I often use option 3 when the subclass provides substantial extension or specification, or if the names would be rather long.
For example, my file system name classes are derived from String
but they greatly extend the String class and have a significantly different
use/meaning:
Directory_entry_name derived from String adds extensive functionality.
File_name derived from Directory_entry_name has rather specialized functions.
Directory_name derived from Directory_entry_name also has rather specialized functions.
Also along with option 1, I usually use an unqualified name for an interface class.
For example I might have a class interence chain:
Text (an interface)
Text_abstract (abstract (base) generalization class)
Text_ASCII (concrete class specific for ASCII coding)
Text_unicode (concrete class specific for unicode coding)
I rather like that the interface and the abstract base class automatically appear first in the sorted list.
Option three more logically follows from the concept of inheritance. Since you're specializing the interface or class, the name should show that it's no longer using the base implementation (if one exists).
There are a multitude of tools to see what a class inherits from, so a concise name indicating the real function of the class will go farther than trying to pack too much type information into the name.

Is Inheritance really needed?

I must confess I'm somewhat of an OOP skeptic. Bad pedagogical and laboral experiences with object orientation didn't help. So I converted into a fervent believer in Visual Basic (the classic one!).
Then one day I found out C++ had changed and now had the STL and templates. I really liked that! Made the language useful. Then another day MS decided to apply facial surgery to VB, and I really hated the end result for the gratuitous changes (using "end while" instead of "wend" will make me into a better developer? Why not drop "next" for "end for", too? Why force the getter alongside the setter? Etc.) plus so much Java features which I found useless (inheritance, for instance, and the concept of a hierarchical framework).
And now, several years afterwards, I find myself asking this philosophical question: Is inheritance really needed?
The gang-of-four say we should favor object composition over inheritance. And after thinking of it, I cannot find something you can do with inheritance you cannot do with object aggregation plus interfaces. So I'm wondering, why do we even have it in the first place?
Any ideas? I'd love to see an example of where inheritance would be definitely needed, or where using inheritance instead of composition+interfaces can lead to a simpler and easier to modify design. In former jobs I've found if you need to change the base class, you need to modify also almost all the derived classes for they depended on the behaviour of parent. And if you make the base class' methods virtual... then not much code sharing takes place :(
Else, when I finally create my own programming language (a long unfulfilled desire I've found most developers share), I'd see no point in adding inheritance to it...
Really really short answer: No. Inheritance is not needed because only byte code is truly needed. But obviously, byte code or assemble is not a practically way to write your program. OOP is not the only paradigm for programming. But, I digress.
I went to college for computer science in the early 2000s when inheritance (is a), compositions (has a), and interfaces (does a) were taught on an equal footing. Because of this, I use very little inheritance because it is often suited better by composition. This was stressed because many of the professors had seen bad code (along with what you have described) because of abuse of inheritance.
Regardless of creating a language with or without inheritances, can you create a programming language which prevents bad habits and bad design decisions?
I think asking for situations where inheritance is really needed is missing the point a bit. You can fake inheritance by using an interface and some composition. This doesnt mean inheritance is useless. You can do anything you did in VB6 in assembly code with some extra typing, that doesn't mean VB6 was useless.
I usually just start using an interface. Sometimes I notice I actually want to inherit behaviour. That usually means I need a base class. It's that simple.
Inheritance defines an "Is-A" relationship.
class Point( object ):
# some set of features: attributes, methods, etc.
class PointWithMass( Point ):
# An additional feature: mass.
Above, I've used inheritance to formally declare that PointWithMass is a Point.
There are several ways to handle object P1 being a PointWithMass as well as Point. Here are two.
Have a reference from PointWithMass object p1 to some Point object p1-friend. The p1-friend has the Point attributes. When p1 needs to engage in Point-like behavior, it needs to delegate the work to its friend.
Rely on language inheritance to assure that all features of Point are also applicable to my PointWithMass object, p1. When p1 needs to engage in Point-like behavior, it already is a Point object and can just do what needs to be done.
I'd rather not manage the extra objects floating around to assure that all superclass features are part of a subclass object. I'd rather have inheritance to be sure that each subclass is an instance of it's own class, plus is an instance of all superclasses, too.
Edit.
For statically-typed languages, there's a bonus. When I rely on the language to handle this, a PointWithMass can be used anywhere a Point was expected.
For really obscure abuse of inheritance, read about C++'s strange "composition through private inheritance" quagmire. See Any sensible examples of creating inheritance without creating subtyping relations? for some further discussion on this. It conflates inheritance and composition; it doesn't seem to add clarity or precision to the resulting code; it only applies to C++.
The GoF (and many others) recommend that you only favor composition over inheritance. If you have a class with a very large API, and you only want to add a very small number of methods to it, leaving the base implementation alone, I would find it inappropriate to use composition. You'd have to re-implement all of the public methods of the encapsulated class to just return their value. This is a waste of time (programmer and CPU) when you can just inherit all of this behavior, and spend your time concentrating on new methods.
So, to answer your question, no you don't absolutely need inheritance. There are, however, many situations where it's the right design choice.
The problem with inheritance is that it conflates the issue of sub-typing (asserting an is-a relationship) and code reuse (e.g., private inheritance is for reuse only).
So, no it's an overloaded word that we don't need. I'd prefer sub-typing (using the 'implements' keyword) and import (kinda like Ruby does it in class definitions)
Inheritance lets me push off a whole bunch of bookkeeping onto the compiler because it gives me polymorphic behavior for object hierarchies that I would otherwise have to create and maintain myself. Regardless of how good a silver bullet OOP is, there will always be instances where you want to employ a certain type of behavior because it just makes sense to do. And ultimately, that's the point of OOP: it makes a certain class of problems much easier to solve.
The downsides of composition is that it may disguise the relatedness of elements and it may be harder for others to understand. With,say, a 2D Point class and the desire to extend it to higher dimensions, you would presumably have to add (at least) Z getter/setter, modify getDistance(), and maybe add a getVolume() method. So you have the Objects 101 elements: related state and behavior.
A developer with a compositional mindset would presumably have defined a getDistance(x, y) -> double method and would now define a getDistance(x, y, z) -> double method. Or, thinking generally, they might define a getDistance(lambdaGeneratingACoordinateForEveryAxis()) -> double method. Then they would probably write createTwoDimensionalPoint() and createThreeDimensionalPoint() factory methods (or perhaps createNDimensionalPoint(n) ) that would stitch together the various state and behavior.
A developer with an OO mindset would use inheritance. Same amount of complexity in the implementation of domain characteristics, less complexity in terms of initializing the object (constructor takes care of it vs. a Factory method), but not as flexible in terms of what can be initialized.
Now think about it from a comprehensibility / readability standpoint. To understand the composition, one has a large number of functions that are composed programmatically inside another function. So there's little in terms of static code 'structure' (files and keywords and so forth) that makes the relatedness of Z and distance() jump out. In the OO world, you have a great big flashing red light telling you the hierarchy. Additionally, you have an essentially universal vocabulary to discuss structure, widely known graphical notations, a natural hierarchy (at least for single inheritance), etc.
Now, on the other hand, a well-named and constructed Factory method will often make explicit more of the sometimes-obscure relationships between state and behavior, since a compositional mindset facilitates functional code (that is, code that passes state via parameters, not via this ).
In a professional environment with experienced developers, the flexibility of composition generally trumps its more abstract nature. However, one should never discount the importance of comprehensibility, especially in teams that have varying degrees of experience and/or high levels of turnover.
Inheritance is an implementation decision. Interfaces almost always represent a better design, and should usually be used in an external API.
Why write a lot of boilerplate code forwarding method calls to a composed member object when the compiler will do it for you with inheritance?
This answer to another question summarises my thinking pretty well.
Does anyone else remember all of the OO-purists going ballistic over the COM implementation of "containment" instead of "inheritance?" It achieved essentially the same thing, but with a different kind of implementation. This reminds me of your question.
I strictly try to avoid religious wars in software development. ("vi" OR "emacs" ... when everybody knows its "vi"!) I think they are a sign of small minds. Comp Sci Professors can afford to sit around and debate these things. I'm working in the real world and could care less. All of this stuff are simply attempts at giving useful solutions to real problems. If they work, people will use them. The fact that OO languages and tools have been commercially available on a wide scale for going on 20 years is a pretty good bet that they are useful to a lot of people.
There are a lot of features in a programming language that are not really needed. But they are there for a variety of reasons that all basically boil down to reusability and maintainability.
All a business cares about is producing (quality of course) cheaply and quickly.
As a developer you help do this is by becoming more efficient and productive. So you need to make sure the code you write is easily reusable and maintainable.
And, among other things, this is what inheritance gives you - the ability to reuse without reinventing the wheel, as well as the ability to easily maintain your base object without having to perform maintenance on all similar objects.
There's lots of useful usages of inheritance, and probably just as many which are less useful. One of the useful ones is the stream class.
You have a method that should be able stream data. By using the stream base class as input to the method you ensure that your method can be used to write to many kinds of streams without change. To the file system, over the network, with compression, etc.
No.
for me, OOP is mostly about encapsulation of state and behavior and polymorphism.
and that is. but if you want static type checking, you'll need some way to group different types, so the compiler can check while still allowing you to use new types in place of another, related type. creating a hierarchy of types lets you use the same concept (classes) for types and for groups of types, so it's the most widely used form.
but there are other ways, i think the most general would be duck typing, and closely related, prototype-based OOP (which isn't inheritance in fact, but it's usually called prototype-based inheritance).
Depends on your definition of "needed". No, there is nothing that is impossible to do without inheritance, although the alternative may require more verbose code, or a major rewrite of your application.
But there are definitely cases where inheritance is useful. As you say, composition plus interfaces together cover almost all cases, but what if I want to supply a default behavior? An interface can't do that. A base class can. Sometimes, what you want to do is really just override individual methods. Not reimplement the class from scratch (as with an interface), but just change one aspect of it. or you may not want all members of the class to be overridable. Perhaps you have only one or two member methods you want the user to override, and the rest, which calls these (and performs validation and other important tasks before and after the user-overridden methods) are specified once and for all in the base class, and can not be overridden.
Inheritance is often used as a crutch by people who are too obsessed with Java's narrow definition of (and obsession with) OOP though, and in most cases I agree, it's the wrong solution, as if the deeper your class hierarchy, the better your software.
Inheritance is a good thing when the subclass really is the same kind of object as the superclass. E.g. if you're implementing the Active Record pattern, you're attempting to map a class to a table in the database, and instances of the class to a row in the database. Consequently, it is highly likely that your Active Record classes will share a common interface and implementation of methods like: what is the primary key, whether the current instance is persisted, saving the current instance, validating the current instance, executing callbacks upon validation and/or saving, deleting the current instance, running a SQL query, returning the name of the table that the class maps to, etc.
It also seems from how you phrase your question that you're assuming that inheritance is single but not multiple. If we need multiple inheritance, then we have to use interfaces plus composition to pull off the job. To put a fine point about it, Java assumes that implementation inheritance is singular and interface inheritance can be multiple. One need not go this route. E.g. C++ and Ruby permit multiple inheritance for your implementation and your interface. That said, one should use multiple inheritance with caution (i.e. keep your abstract classes virtual and/or stateless).
That said, as you note, there are too many real-life class hierarchies where the subclasses inherit from the superclass out of convenience rather than bearing a true is-a relationship. So it's unsurprising that a change in the superclass will have side-effects on the subclasses.
Not needed, but usefull.
Each language has got its own methods to write less code. OOP sometimes gets convoluted, but I think that is the responsability of the developers, the OOP platform is usefull and sharp when it is well used.
I agree with everyone else about the necessary/useful distinction.
The reason I like OOP is because it lets me write code that's cleaner and more logically organized. One of the biggest benefits comes from the ability to "factor-up" logic that's common to a number of classes. I could give you concrete examples where OOP has seriously reduced the complexity of my code, but that would be boring for you.
Suffice it to say, I heart OOP.
Absolutely needed? no,
But think of lamps. You can create a new lamp from scratch each time you make one, or you can take properties from the original lamp and make all sorts of new styles of lamp that have the same properties as the original, each with their own style.
Or you can make a new lamp from scratch or tell people to look at it a certain way to see the light, or , or, or
Not required, but nice :)
Thanks to all for your answers. I maintain my position that, strictly speaking, inheritance isn't needed, though I believe I found a new appreciation for this feature.
Something else: In my job experience, I have found inheritance leads to simpler, clearer designs when it's brought in late in the project, after it's noticed a lot of the classes have much commonality and you create a base class. In projects where a grand-schema was created from the very beginning, with a lot of classes in an inheritance hierarchy, refactoring is usually painful and dificult.
Seeing some answers mentioning something similar makes me wonder if this might not be exactly how inheritance's supposed to be used: ex post facto. Reminds me of Stepanov's quote: "you don't start with axioms, you end up with axioms after you have a bunch of related proofs". He's a mathematician, so he ought to know something.
The biggest problem with interfaces is that they cannot be changed. Make an interface public, then change it (add a new method to it) and break million applications all around the world, because they have implemented your interface, but not the new method. The app may not even start, a VM may refuse to load it.
Use a base class (not abstract) other programmers can inherit from (and override methods as needed); then add a method to it. Every app using your class will still work, this method just won't be overridden by anyone, but since you provide a base implementation, this one will be used and it may work just fine for all subclasses of your class... it may also cause strange behavior because sometimes overriding it would have been necessary, okay, might be the case, but at least all those million apps in the world will still start up!
I rather have my Java application still running after updating the JDK from 1.6 to 1.7 with some minor bugs (that can be fixed over time) than not having it running it at all (forcing an immediate fix or it will be useless to people).
//I found this QA very useful. Many have answered this right. But i wanted to add...
1: Ability to define abstract interface - E.g., for plugin developers. Of course, you can use function pointers, but this is better and simpler.
2: Inheritance helps model types very close to their actual relationships. Sometimes a lot of errors get caught at compile time, because you have the right type hierarchy. For instance, shape <-- triangle (lets say there is a lot of code to be reused). You might want to compose triangle with a shape object, but shape is an incomplete type. Inserting dummy implementations like double getArea() {return -1;} will do, but you are opening up room for error. That return -1 can get executed some day!
3: void func(B* b); ... func(new D()); Implicit type conversion gives a great notational convenience since Derived is Base. I remember having read Straustrup saying that he wanted to make classes first class citizens just like fundamental data types (hence overloading operators etc). Implicit conversion from Derived to Base, behaves just like an implicit conversion from a data type to broader compatible one (short to int).
Inheritance and Composition have their own pros and cons.
Refer to this related SE question on pros of inheritance and cons of composition.
Prefer composition over inheritance?
Have a look at the example in this documentation link:
The example shows different use cases of overriding by using inheritance as a mean to achieve polymorphism.
In the following, inheritance is used to present a particular property for all of several specific incarnations of the same type thing. In this case, the GeneralPresenation has a properties that are relevant to all "presentation" (the data passed to an MVC view). The Master Page is the only thing using it and expects a GeneralPresentation, though the specific views expect more info, tailored to their needs.
public abstract class GeneralPresentation
{
public GeneralPresentation()
{
MenuPages = new List<Page>();
}
public IEnumerable<Page> MenuPages { get; set; }
public string Title { get; set; }
}
public class IndexPresentation : GeneralPresentation
{
public IndexPresentation() { IndexPage = new Page(); }
public Page IndexPage { get; set; }
}
public class InsertPresentation : GeneralPresentation
{
public InsertPresentation() {
InsertPage = new Page();
ValidationInfo = new PageValidationInfo();
}
public PageValidationInfo ValidationInfo { get; set; }
public Page InsertPage { get; set; }
}