Is it correct to return an object which class is not the expected class? - oop

Well, i hope you understand me. I have two classes, A and B. B is subclass of A. They have the same public methods and means the same thing, but B does some things a little different, so it has additional methods and attributes that only uses itself. Let say, class A implements a method newFromWizard that interactively creates an object. Can I implement logic for, depending on the user input, create an object A or and object B in the newFromWizard method of A. I mean, can i create a B object from that method of A? Or i need to implement that elsewhere? How is the best way to do it? In practice, i can. But, it is correct for OOP?
By the way, if that matters, i'm using Smalltalk.

Yes, this is a well-known pattern in OO. In the Objective-C Cocoa libraries you'll find it applied systematically, and is known as class clusters. The result is that the Cocoa libraries are much easier to understand than the equivalent c# or java ones. It allows the hiding of a inheritance hierarchy behind an abstract class that has class side creation methods that return subclasses.

public class A{
public B method(){
B b = new B();
return b;
}
}
class B extends A{
}
If this is what you're talking about, it's valid.

I would say that it's not intuitive way of doing things. Let's simplify it and say that you just redefine new. Then in some point you do A new and get an instance of B. The thing that they are similar makes it not so bad. But imagine that someone else starts working with your code. And hew knows that message new should result in creation of the instance of the receiver. And then something goes different. I'd say that conceptually it's wrong. Why now to implements some builder class? And have there something like
createInstanceOfAB
|className|
className := "do what you need".
^ className asClass new.
This is a more clear way.
Once again you can make new… method to do whatever you want, even shoot fireworks, but most of the people will expect it to create instance of the same class

I think you shouldn't worry too much about whether it is "clean OO" to return an instance of a subclass. It's being used and done so often because it is very helpful and makes your code very readable compared to somme kind of factories and stuff.
My biggest concern here would be that you should name your class method carefully. Don't use #new is probably the most important rule, but you should always use a name that already says: give me an instance of what is appropriate right now.
I'd say this is not limited to subclasses, such a method can even return objects that do not inherit from the class. In a dynamically typed language, this is okay. Remember, we're in a dynamically typed language, so as long as you have polymorphic interfaces, the class of an object is not really important to its users as long as it responds to your message sends...

Related

Is it discouraged to down-cast a returned instance to gain functionality that is not exposed via the returned class type?

This is the basic scenario:
A method returns a class of type A, but after looking at the internal workings of the code it is found safe to assume that it actually returns B (a subclass of A). Is it then valid to do something like this? Or would you highly discourage it because it is accessing protected data (at least):
Assume that you do not maintain this code that implements the method as well. I.e, your software could ship with a different implementation of this (well established) method.
A returnedData = executeMethod();
if(returnedData instanceof B)
{
((B)returnedData).someFunctionNotExposedThroughAIsItProtected();
//Use it as B, safe but non OOP and accessing protected functionality?
}else
writeAFallBackOfSomeSort();
The key point is the if(returnedData instanceof B): if such a statement exist, it is proven that the returned object is a B (which in turn also includes A), so using B public method is safe.
In pure OOP sense this is not "elegant", but it is often the pragmatic way to go.
Think a while: a Dog is an Animal, but is unlikely that Animal has a do-nothing bark method, otherwise -for completeness- it must have all methods for all possible animals may have, thus making Animal a sort of "God Object" (a well known anti-pattern).
It is more pragmatic once you've got an Animal, ask it to bark only after you recognized it is a Dog. You can have then more Dog subclasses (representing different dog races) barking differently, but bark belongs to Dogs, not Animal in general.
The problem now becomes: is it correct to suppose an Animal could be a Dog? If you can check it, why not!
Use OOP as a technique where convenient, not as a religion to serve.
Consider also that the answer can change depending on the language used and on what feature it has around objects and the way it define what a "object" is. Where no runtime dispatch exist (or where runtime dispatch is single and you need multiple) this can be even a well established method.
It most certainly is discouraged.
A method of an API declares a specific return type because that's what the API developer decided to declare. It creates a contract essentially saying "expect this type and nothing else". If the API developer didn't want to expose another type, (s)he probably had a good reason for that.
The internal implementation of the method should, in the general case, never concern you. The API developer can change it at any time, and in this case you are the one responsible for the consequences, not her/him.
Granted, your workaround is OK, as long as the sole contents of writeAFallBackOfSomeSort() is not
private void writeAFallBackOfSomeSort() {
//TODO: I'll implement this later
}
.

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.

"Has a" vs "Is a" - code smells for deciding

I wrote this yesterday, in a class Foo inheriting from Bar:
public override void AddItem(double a, int b)
{
//Code smell?
throw new NotImplementedException("This method not usable for Foo items");
}
Wondered subsequently if this is a possible indication that I should be using a Bar, rather than inheriting from it.
What other 'code smells' could help to chose between inheritance and composition?
EDIT I should add that this is a snippet, there are other methods which are in common, I just didn't want to go into too much detail. I have to analyse the implications of switching to composition, and wondered if there might be other 'code smells' which could help to tip the balance.
The example you gave above is clearly a code smell. The AddItem method is a behaviour of the base class Bar. If Foo doesn't support the AddItem behaviour, it shouldn't inherit from Bar.
Let's think of a more realistic (C++) example. Let's say you had the following class:
class Animal
{
void Breathe() const=0;
}
class Dog : public Animal
{
// Code smell
void Breathe() { throw new NotSupportedException(); }
}
The base abstract class Animal provides a pure virtual Breathe() method, because an animal must breathe to survive. If it doesn't breathe, then by definition it is not an animal.
By creating a new class Dog which inherits from Animal but doesn't support the Breathe() behaviour, you are breaking the contract stipulated by the Animal class. The poor dog won't survive!
The simple rule for public inheritance is that you should only do it if the derived class object truly "is a" base class object.
In your particular example:
Foo doesn't support the AddItem() behaviour stipulated by the Bar contract.
Therefore, by definition, Foo is "not a" Bar, and shouldn't inherit from it.
So why would you inherit from Bar, if Foo without extensions doesn't behave like Bar?
Come to think of it, I wouldn't even declare a method like 'AddItem' as virtual in the base class.
No! A square might be a rectangle, but
a Square object is definitely not a
Rectangle object. Why? Because the
behavior of a Square object is not
consistent with the behavior of a
Rectangle object. Behaviorally, a
Square is not a Rectangle! And it is
behavior that software is really all
about.
From The Liskov Substitution Principle in Object Mentor.
Yes, that you have to "un-implement" methods is an indication that perhaps you shouldn't use an "is-a" relationship. Your Foos don't seem to really be Bars.
But start by thinking about your Foos and Bars. Are Foos Bars? Can you draw sets and subsets on a paper, and will every Foo (that is, every memeber of the Foo class) also be a Bar (that is, a member of the Bar class)? If not, you probably don't want to use inheritance.
Another code smell that indicates that Foos aren't really Bars, and that Foo shouldn't inherit Bar, is that you can't use polymorphism. Lets say you have a method that takes a Bar as an argument, but it won't be able to handle a Foo. (Perhaps because it calls the AddItem method in its argument!) You'll have to add a check, or handle the NotImplementedException, making the code complicated and hard to understand. (And smelling!)
Of course there's the direct converse, if your Foo implements a lot of interface that just forwards messages to the Bar that it owns, this could indicate that it should be a Bar. Only could, though, smells aren't always correct.
While the example above probably indicates that something goes wrong, NotImplementedException itself is not wrong always. It's all about the contract of superclass and about subclass implementing this contract. If your superclass has such method
// This method is optional and may be not supported
// If not supported it should throw NotImplementedException
// To find out if it is supported or not, use isAddItemSupported()
public void AddItem(double a, int b){...}
Then, not supporting this method is still ok with the contract. If it is not supported, you probably should disable corresponding action in UI. So if you are ok with such contract, then subclass implements it correctly.
Another option when client explicitly declares that it does not use all class methods and is never going to. Like this
// This method never modifies orders, it just iterates over
// them and gets elements by index.
// We decided to be not very bureaucratic and not define ReadonlyList interface,
// and this is closed-source 3rd party library so you can not modify it yourself.
// ha-ha-ha
public void saveOrders(List<Order> orders){...}
Then it is ok to pass there implementaion of List that does not support add,remove and other mutators. Just document it.
// Use with care - this implementation does not implement entire List contract
// It does not support methods that modify the content of the list.
public ReadonlyListImpl implements List{...}
While having your code to define all your contract is good, as it let's your compiler to check if you violate the contract, sometimes it is not reasonable and you have to resort to weakly defined contracts, like comments.
In short words it comes to the question, if you really can safely use your subclass as superclass, taking into account that superclass is defined by its contract which is not only code.
The .Net framework has examples like this, particularly in the System.IO namespace - some readers don't implements all of their base class properties / methods and will throw exceptions if you try to use them.
E.g. Stream has a position property, but some streams don't support this.
Composition is preferable to inheritance as it reduces complexity. Better approach would be to use constructor injection and keep a reference to Bar in your Foo class.

A use for multiple inheritance?

Can anyone think of any situation to use multiple inheritance? Every case I can think of can be solved by the method operator
AnotherClass() { return this->something.anotherClass; }
Most uses of full scale Multiple inheritance are for mixins. As an example:
class DraggableWindow : Window, Draggable { }
class SkinnableWindow : Window, Skinnable { }
class DraggableSkinnableWindow : Window, Draggable, Skinnable { }
etc...
In most cases, it's best to use multiple inheritance to do strictly interface inheritance.
class DraggableWindow : Window, IDraggable { }
Then you implement the IDraggable interface in your DraggableWindow class. It's WAY too hard to write good mixin classes.
The benefit of the MI approach (even if you are only using Interface MI) is that you can then treat all kinds of different Windows as Window objects, but have the flexibility to create things that would not be possible (or more difficult) with single inheritance.
For example, in many class frameworks you see something like this:
class Control { }
class Window : Control { }
class Textbox : Control { }
Now, suppose you wanted a Textbox with Window characteristics? Like being dragable, having a titlebar, etc... You could do something like this:
class WindowedTextbox : Control, IWindow, ITexbox { }
In the single inheritance model, you can't easily inherit from both Window and Textbox without having some problems with duplicate Control objects and other kinds of problems. You can also treat a WindowedTextbox as a Window, a Textbox, or a Control.
Also, to address your .anotherClass() idiom, .anotherClass() returns a different object, while multiple inheritance allows the same object to be used for different purposes.
I find multiple inheritance particularly useful when using mixin classes.
As stated in Wikipedia:
In object-oriented programming
languages, a mixin is a class that
provides a certain functionality to be
inherited by a subclass, but is not
meant to stand alone.
An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality.
But they may also inherit from other classes as part of their normal class structure, so it is quite common for these classes to use multiple inheritance in this respect.
An example of multiple inheritance:
class Animal
{
virtual void KeepCool() const = 0;
}
class Vertebrate
{
virtual void BendSpine() { };
}
class Dog : public Animal, public Vertebrate
{
void KeepCool() { Pant(); }
}
What is most important when doing any form of public inheritance (single or multiple) is to respect the is a relationship. A class should only inherit from one or more classes if it "is" one of those objects. If it simply "contains" one of those objects, aggregation or composition should be used instead.
The example above is well structured because a dog is an animal, and also a vertebrate.
Most people use multiple-inheritance in the context of applying multiple interfaces to a class. This is the approach Java and C#, among others, enforce.
C++ allows you to apply multiple base classes fairly freely, in an is-a relationship between types. So, you can treat a derived object like any of its base classes.
Another use, as LeopardSkinPillBoxHat points out, is in mix-ins. An excellent example of this is the Loki library, from Andrei Alexandrescu's book Modern C++ Design. He uses what he terms policy classes that specify the behavior or the requirements of a given class through inheritance.
Yet another use is one that simplifies a modular approach that allows API-independence through the use of sister-class delegation in the oft-dreaded diamond hierarchy.
The uses for MI are many. The potential for abuse is even greater.
Java has interfaces. C++ has not.
Therefore, multiple inheritance can be used to emulate the interface feature.
If you're a C# and Java programmer, every time you use a class that extends a base class but also implements a few interfaces, you are sort of admitting multiple inheritance can be useful in some situations.
I think it would be most useful for boilerplate code. For example, the IDisposable pattern is exactly the same for all classes in .NET. So why re-type that code over and over again?
Another example is ICollection. The vast majority of the interface methods are implemented exactly the same. There are only a couple of methods that are actually unique to your class.
Unfortunately multiple-inheritance is very easy to abuse. People will quickly start doing silly things like LabelPrinter class inherit from their TcpIpConnector class instead of merely contain it.
One case I worked on recently involved network enabled label printers. We need to print labels, so we have a class LabelPrinter. This class has virtual calls for printing several different labels. I also have a generic class for TCP/IP connected things, which can connect, send and receive.
So, when I needed to implement a printer, it inherited from both the LabelPrinter class and the TcpIpConnector class.
I think fmsf example is a bad idea. A car is not a tire or an engine. You should be using composition for that.
MI (of implementation or interface) can be used to add functionality. These are often called mixin classes.. Imagine you have a GUI. There is view class that handles drawing and a Drag&Drop class that handles dragging. If you have an object that does both you would have a class like
class DropTarget{
public void Drop(DropItem & itemBeingDropped);
...
}
class View{
public void Draw();
...
}
/* View you can drop items on */
class DropView:View,DropTarget{
}
It is true that composition of an interface (Java or C# like) plus forwarding to a helper can emulate many of the common uses of multiple inheritance (notably mixins). However this is done at the cost of that forwarding code being repeated (and violating DRY).
MI does open a number of difficult areas, and more recently some language designers have taken decisions that the potential pitfalls of MI outweigh the benefits.
Similarly one can argue against generics (heterogeneous containers do work, loops can be replaced with (tail) recursion) and almost any other feature of programming languages. Just because it is possible to work without a feature does not mean that that feature is valueless or cannot help to effectively express solutions.
A rich diversity of languages, and language families makes it easier for us as developers to pick good tools that solve the business problem at hand. My toolbox contains many items I rarely use, but on those occasions I do not want to treat everything as a nail.
An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality.
This example doesn't really illustrate the usefulness of multiple inheritance. What being defined here is an INTERFACE. Multiple inheritance allows you to inherit behavior as well. Which is the point of mixins.
An example; because of a need to preserve backwards compatibility I have to implement my own serialization methods.
So every object gets a Read and Store method like this.
Public Sub Store(ByVal File As IBinaryWriter)
Public Sub Read(ByVal File As IBinaryReader)
I also want to be able to assign and clone object as well. So I would like this on every object.
Public Sub Assign(ByVal tObject As <Class_Name>)
Public Function Clone() As <Class_Name>
Now in VB6 I have this code repeated over and over again.
Public Assign(ByVal tObject As ObjectClass)
Me.State = tObject.State
End Sub
Public Function Clone() As ObjectClass
Dim O As ObjectClass
Set O = New ObjectClass
O.State = Me.State
Set Clone = 0
End Function
Public Property Get State() As Variant
StateManager.Clear
Me.Store StateManager
State = StateManager.Data
End Property
Public Property Let State(ByVal RHS As Variant)
StateManager.Data = RHS
Me.Read StateManager
End Property
Note that Statemanager is a stream that read and stores byte arrays.
This code is repeated dozens of times.
Now in .NET i am able to get around this by using a combination of generics and inheritance. My object under the .NET version get Assign, Clone, and State when they inherit from MyAppBaseObject. But I don't like the fact that every object inherits from MyAppBaseObject.
I rather just mix in the the Assign Clone interface AND BEHAVIOR. Better yet mix in separately the Read and Store interface then being able to mix in Assign and Clone. It would be cleaner code in my opinion.
But the times where I reuse behavior are DWARFED by the time I use Interface. This is because the goal of most object hierarchies are NOT about reusing behavior but precisely defining the relationship between different objects. Which interfaces are designed for. So while it would be nice that C# (or VB.NET) had some ability to do this it isn't a show stopper in my opinion.
The whole reason that this is even an issue that that C++ fumbled the ball at first when it came to the interface vs inheritance issue. When OOP debuted everybody thought that behavior reuse was the priority. But this proved to be a chimera and only useful for specific circumstances, like making a UI framework.
Later the idea of mixins (and other related concepts in aspect oriented programming) were developed. Multiple inheritance was found useful in creating mix-ins. But C# was developed just before this was widely recognized. Likely an alternative syntax will be developed to do this.
I suspect that in C++, MI is best use as part of a framework (the mix-in classes previously discussed). The only thing I know for sure is that every time I've tried to use it in my apps, I've ended up regretting the choice, and often tearing it out and replacing it with generated code.
MI is one more of those 'use it if you REALLY need it, but make sure you REALLY need it' tools.
The following example is mostly something I see often in C++: sometimes it may be necessary due to utility classes that you need but because of their design cannot be used through composition (at least not efficiently or without making the code even messier than falling back on mult. inheritance). A good example is you have an abstract base class A and a derived class B, and B also needs to be a kind of serializable class, so it has to derive from, let's say, another abstract class called Serializable. It's possible to avoid MI, but if Serializable only contains a few virtual methods and needs deep access to the private members of B, then it may be worth muddying the inheritance tree just to avoid making friend declarations and giving away access to B's internals to some helper composition class.
I had to use it today, actually...
Here was my situation - I had a domain model represented in memory where an A contained zero or more Bs(represented in an array), each B has zero or more Cs, and Cs to Ds. I couldn't change the fact that they were arrays (the source for these arrays were from automatically generated code from the build process). Each instance needed to keep track of which index in the parent array they belonged in. They also needed to keep track of the instance of their parent (too much detail as to why). I wrote something like this (there was more to it, and this is not syntactically correct, it's just an example):
class Parent
{
add(Child c)
{
children.add(c);
c.index = children.Count-1;
c.parent = this;
}
Collection<Child> children
}
class Child
{
Parent p;
int index;
}
Then, for the domain types, I did this:
class A : Parent
class B : Parent, Child
class C : Parent, Child
class D : Child
The actually implementation was in C# with interfaces and generics, and I couldn't do the multiple inheritance like I would have if the language supported it (some copy paste had to be done). So, I thought I'd search SO to see what people think of multiple inheritance, and I got your question ;)
I couldn't use your solution of the .anotherClass, because of the implementation of add for Parent (references this - and I wanted this to not be some other class).
It got worse because the generated code had A subclass something else that was neither a parent or a child...more copy paste.

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