views:

460

answers:

9

How do you name different classes / interfaces you create? Sometimes I don't have implementation information to add to the implementation name - like interface FileHandler and class SqlFileHandler.

hen this happens I usually name the interface in the "normal" name, like Truck and name the actual class TruckClass.

How do you name interfaces and classes in this regard?

+1  A: 

The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.

tzaman
That's just a throwback from COM programming. Why would you want to tell an interface from a class?
John Topley
+1  A: 

Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:

IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations

The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.

I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.

Andy White
+21  A: 

Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck. An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc. When you are using the Interface Truck in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just crappy hungarian style notation tautology that adds nothing but more stuff to type to your code.

All modern Java IDEs mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.

If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions is AbstractTruck. Since only the sub-classes will every see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck instead. But since Abstract classes should never be part of any public facing interface it is an acceptable exception to the rule.

And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?

The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.

Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No you see. List and ArrayList and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principal as well.

Also if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even adhere to in a consistent manner. If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have an situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface.

fuzzy lollipop
`it isn't an ITruck it is a Truck` - Actually, it's a *blueprint* for the basic framework of a Truck.
Robert Harvey
actually it is a contract for the interface of the Type Truck. Intefaces are __Types__ in Java.
fuzzy lollipop
+1 - very refreshing to hear this logic.
Adam Paynter
actually its a proxy to some object which implements the contract specified by 'Truck', which is why Truck is a bad example since its not really all that functional an interface.
Justin
its not a Proxy a proxy is something __COMPLETELY__ different in scope and semantics. A proxy implies an intermediary that substitutes behavior on behalf of something else. That is __NOT__ what an interface does, actually that is the exactly __OPPOSITE__ of what an Interface is for in Java. A CementTruck subclass __IS__ a Type of Truck if it implements Truck. It has __NOTHING__ to do with the concept of a proxy in any way shape or form.
fuzzy lollipop
don't confuse technically how it runs in java with how people use it.
Justin
Justin, you don't understand what the word Proxy means then. If you think Java Interface == Proxy then you need to re-read what an Interface actually is and what function a Proxy plays. You can substitute an Interface for a Implementation but in __NO__ way does it proxy anything to the Implementation. It just hides any Implementation specific methods or properties. You are still interacting with the exact same instance of the Implementation, there is no delegation or proxying going on.
fuzzy lollipop
Substituting an Interface for an Implementation is called down-casting, and since an Interface can't have any implementation code how can it Proxy ( act on behalf ) of another class.
fuzzy lollipop
People use interfaces for two reasons: functional abstraction (very common) and type abstraction (less common and more of a crutch to reduce runtime dependencies). Look at Remote proxy, Transactional Proxy, in both cases you are acting through the interface as if it were a proxy and you don't really care about the object which implements your interface, you just care about what it does.
Justin
You still don't understand that RemoteProxy maybe an Interface but it still has an Implemenation that is the actual Proxy. An Interface alone has __NO__ functionality. You are confusing an Interface that is __NAMED__ RemoteProxy with something that has an Implementation that __IS__ actually doing the work on behalf of another class. The Interface has __NO__ responsibility or functionality in the process. Don't confuse the __NAME__ of the Interface with the fact that it can't actually __DO__ anything without an Implementation.
fuzzy lollipop
You are __NOT__ "acting" through an Interface you are "acting" through an Implementation that conforms to the __contract__ that the Interface stipulates. The Interface has __NO__ code, the probably magically created at compile time or deployment time actually Implemenation of that Interface is the real Proxy that acts on behalf of the client. In both your cases the interface is __NOT__ a proxy, it is a contract that the actual proxy class is to implement. The semantics of the differences are __very__ important.
fuzzy lollipop
A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. Typically one instance of the complex object is created, and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Interfaces in this scenario can't actually do anything, since they have __no__ code.
fuzzy lollipop
+2  A: 

TruckClass sounds like it were a class of Truck, I think that recommended solution is to add Impl suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List interface and implementations: ArrayList or LinkedList), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl is the solution.

Luno
You beat me to it. But yes, the Impl suffix is a good alternative.
Cesar
I agree, having "Truck" as the interface and "TrunkImpl" as the class name seems like the most common way to do it in Java.
Jon
Classes don't need a suffix to show that they're implementations of an interface; that's what the `implements` keyword is for. If I had to see `Impl` after all of my class names, I think I would shoot myself.
Robert Harvey
common doesn't mean the same thing as correct, Robert Harvey is 100% correct.
fuzzy lollipop
@Robert Harvey Then what can I do if I have an interface with just one implementation and no specific information to include in its name?
Amir Rachum
Well, I'm in the camp that says *distinguish your interface names, not your class names.* What if your `Truck` class implements the `Vehicle` interface? Then naming your class `TruckImpl` wouldn't make any sense. But you *could* name your interface `VehicleInterface` or `IVehicle` (or even, simply `Vehicle`, if that's your sensibility), and call your class `Truck` with no problems.
Robert Harvey
@Robert Harvey if the interface would represent a generic vehicle and the truck is a "specialization" of a vehicle, that would be fine. But it's just happens to be an example from a software for a truck company. So it SHOULD say truck when using the interface. Otherwise it's just awkward.
Amir Rachum
if you have one implementation and one interface you probably should not have an interface to begin with.
fuzzy lollipop
+12  A: 

The name of the interface should describe the abstract concept the interface represents. Any implementation class should have some sort of specific traits that can be used to give it a more specific name.

If there is only one implementation class and you can't think of anything that makes it specific (implied by wanting to name it -Impl), then it looks like there is no justification to have an interface at all.

Michael Borgwardt
Very good point about the `Impl`.
Pindatjuh
I've seen many systems with an interface and a single class to implement that interface, like IXxx and Xxx, or Xxx and XxxImpl. I don't see the point. If you only have one implementation, why bother breaking it into two types? All you gained was having to write all the declarations twice and keep them in sync.
Jay
@Jay: That kind of thing is usually done by people who are very orthodox about unit testing everything in isolation and no knowledge about (or access to) mocking frameworks that allow mocking concrete classes.
Michael Borgwardt
@Borgwardt: I was thinking that it was done by old C programmers who think that, just like in C they had to create a .h for every .c module, think that in Java they must create an interface for every class! :-)
Jay
A: 

I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?

Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.

mfx
`TruckLike`?...
Robert Harvey
If the pattern holds (`Comparable`, `Serializable`, ...), then it should be `Truckable`.
Bert F
in a real world implementation Truck would probably extend a Vehicle interface that supplied some even more common behaviors and properties.
fuzzy lollipop
@Robert Harvey, @Bert F: Nope, the question is, what do Trucks do? And do they do it in your particular code? E.g. they might be "Ridable".
Mecki
@Mecki - it was a joke - I'm sure @Robert's comment was too.
Bert F
+3  A: 

I tend to follow the pseudo-conventions established by Java Core/Sun, e.g. in the Collections classes:

  • List - interface for the "conceptual" object
  • ArrayList - concrete implementation of interface
  • LinkedList - concrete implementation of interface
  • AbstractList - abstract "partial" implementation to assist custom implementations

I used to do the same thing modeling my event classes after the AWT Event/Listener/Adapter paradigm.

Bert F
I would +1 this, execpt for the poor recommendation to suffix things with JDO and the like, that is what packages are for.
fuzzy lollipop
@fuzzy - I get what you are saying and that is exactly how I started out. However, in practice, the readability was poor for code that referenced both classes when only the package was used distinguished the classes. The readability improved with the suffixes. The code that didn't refer to both classes tended to use the interface anyway, so the readability wasn't harmed there by the names.
Bert F
@fuzzy - but since you seem to dislike my example naming convention, I'll remove them so the core idea of following the Sun-established conventions is detracted from by people who don't like my naming convention.
Bert F
I like the way you think Bert F :-) And to address the "readiblity" of same named classes I only import the most commonly used version and use a fully qualified name for the one I only need to reference once or twice. java.util.Date vs java.sql.Date is a good example in the JDK. I import the java.util version of Date and fully qualify any references to java.sql.Date where needed.
fuzzy lollipop
+1  A: 

I use both conventions:

If the interface is a specific instance of a a well known pattern (e.g. Service, DAO), then it may not need an "I" (e.g UserService, AuditService, UserDao) all work fine without the "I", because the post-fix determines the meta pattern.

But, if you have something one-off or two-off (usually for a callback pattern), then it helps to distinguish it from a class (e.g. IAsynchCallbackHandler, IUpdateListener, IComputeDrone). These are special purpose interfaces designed for internal use, occasionally the IInterface calls out attention to the fact that an operand is actually an interface, so at first glance it is immediately clear.

In other cases you can use the I to avoid colliding with other commonly known concrete classes (ISubject, IPrincipal vs Subject or Principal).

Justin
not even consistently doing it poorly :-)
fuzzy lollipop
those "Service" and "DAO" suffixes should be packages, then you don't need that useless suffix either.
fuzzy lollipop
I don't really find package qualification clarifies anything in terms of readability (though technically it disambiguates). Consider hibernate's Session which collides with every other Session out there. Any code with both is a mess to think through and read.
Justin
A: 

I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).

So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.

in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).

Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.

For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).

I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.

MetroidFan2002
Nothing about the concept of Inversion of Control or Dependency Injection requires Interfaces for single implemenations of classes, a few popular implementations of IoC Containers force you to do silly things with Interfaces for single implementations. Simply passing in objects to a constructor is the original "Dependency Injection". And as for mocks, use something like Mockito and just have it mock out based on the actual class.
fuzzy lollipop
Right, and then when you have a bug in the actual class, you can't isolate the bug to the actual class. Since, after all, the class is "tested" by its use. But it's not. You can't achieve isolation by using actual code. When two tests fail - one for the class, and one with the class that uses the class, which is at fault? Isolating via interfaces makes only ONE test fail - the test for the actual class, not the test for the class that uses the interface that the class implements.
MetroidFan2002
you don't understand what Mockito does with the "actual class"
fuzzy lollipop
You don't understand how easily a shared mock implementation can be shared for test reuse, rather than a custom mock using a mocking framework for different tests, re-inventing the wheel via setup code each time. Custom mock implementations are much cleaner in the long run, and have the benefit of being able to be documented - unlike dynamically generated proxies.Furthermore, unless you mock out *every* method in your implementing class, there's no guarantee that the unit under test doesn't have a dependency on the actual implementation - it should be able to work regardless.
MetroidFan2002