Java Interfaces/Implementation Naming Convention

Java Interfaces/Implementation naming convention

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 that implements Truck.

When you are using the Interface in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just Hungarian style notation tautology that adds nothing but more stuff to type to your code.

All modern Java IDE's 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, could be something like AbstractTruck. Since only the sub-classes will ever 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 or DefaultTruck instead since the abstract is in the definition. But since Abstract classes should never be part of any public facing interface I believe it is an acceptable exception to the rule. Making the constructors protected goes a long way to crossing this divide.

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 principle 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 internally 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 a 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 in most cases.

However, in general for maintainability, testability, mocking, it's best practice to provide interfaces. See this answer for more details.

Also Refer this interesting article by Martin Fowler on this topic of InterfaceImplementationPair

Interface naming in Java

I prefer not to use a prefix on interfaces:

  • The prefix hurts readability.

  • Using interfaces in clients is the standard best way to program, so interfaces names should be as short and pleasant as possible. Implementing classes should be uglier to discourage their use.

  • When changing from an abstract class to an interface a coding convention with prefix I implies renaming all the occurrences of the class --- not good!

Java Interface Naming Conventions

There's no "one" correct answer here. Naming is quite subjective but what matters the most is that it should be consistent throughout the code base. I would just like to add (to @fge's answer) some more options for you:

  • Making the Interfaces more generic.

    EmployeeRepository implements Repository
    DocumentMappingService implements MappingService
  • Calling your single implementations "defaults".

    DefaultEmployeeRepository implements EmployeeRepository
    DefaultDocumentMappingService implements DocumentMappingService
  • Calling your base implementations (if, sometimes extended) as "support".

    EmployeeRepositorySupport implements EmployeeRepository
    DocumentMappingServiceSupport implements DocumentMappingService

I come across these naming conventions a lot when using the Spring Framework.


Edit : In response to user nyxz's comment about the -Base or Base- convention.

Like I said before, naming is subjective and there's nothing wrong with using the Base nomenclature as such. But, personally, I don't prefer using it. Here's why:

  1. If your implementations would mostly be used directly, then the code instantiating the classes leaves an impression of breaking the OOP hierarchy. That perhaps a specific derived class should have been instantiated.

  2. If your implementations would mostly be extended from, then the word Base becomes redundant in a way. You're extending from it so, of course, it's a base class. Duh!

The 2nd point mostly applies to peripheral classes in your project. Extension points that you provide when you're publishing a framework or library to be used and extended in other projects.

On the other hand, a good use case for using the Base terminology would be for classes internal to your framework that factor common functionality out of other peripheral classes. Since, these classes aren't supposed to be instantiated directly, they are marked abstract, which is in line with the 1st point.

Here's the Adapter hierarchy from the Android framework as an example:

  • Interface hierarchy.

    public interface Adapter
    public interface ListAdapter extends Adapter
    public interface SpinnerAdapter extends Adapter
  • The abstract Base class that factors out the common behaviour and interface implementations.

    public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter
  • Peripheral classes that are mostly instantiated but sometimes extended by an Android application.

    public class SimpleAdapter extends BaseAdapter implements Filterable
    public class ArrayAdapter<T> extends BaseAdapter implements Filterable

Naming Convention for Class/Interface Default Implementation

A common pattern in the Java world is call the abstract, incomplete implementation AbstractSomething; for example AbstractList or AbstractButton. Both the interface and the abstract class are exposed to clients. The idea behind this is that the abstract class serves as a starting point when using the API. This is useful especially for interfaces that define many methods and complex contracts, such as java.util.List. Most of the methods of the interface are implemented in terms of a minimal set of abstract methods that the client has to provide.

For example, to implement a list based on AbstractList you only have to provide an implementation for the get(index) and size() methods. All other operations - iterators, indexOf, subList, hashCode ... - in the end delegate to these two.

How to name repository and service interfaces?

I think that there are roughly two approaches to naming in DDD:

1) Stereotype based. This is where you include class stereotype in its name. For example:

QuestionsRepository, TaxCalculatingService etc

2) Domain based. In this approach you use only domain language and omit any stereotypes in the class names. For example:

Questions (or AllQuestions), TaxCalculator etc.

Implementation classes would be named like SqlQuestions or InMemoryQuestions.

I tried both but I now prefer 2nd option as it seems to be more aligned with DDD mindset. It seems more readable and have a better signal-to-noise ratio. Following is a quote from a great article on repositories by Phil Calçado:

The concept of a Repository as a list of objects is not too hard to understand but it is very common for those classes to end up with methods that are not related to lists at all.

After coaching many teams in the adoption of a Ubiquitous Language and related patterns, I’ve found out that the best way to make people remember that Repositories are not DAO-like classes starts with how you name them.

Years ago Rodrigo Yoshima told me about his convention when naming Repositories. Instead of the more common naming style displayed below:

class OrderRepository {
List<Order> getOrdersFor(Account a){...}
}

He promotes this:

class AllOrders {
List<Order> belongingTo(Account a){...}
}

It looks like a small change but it helps a lot...

The whole article is well worth reading and bookmarking.

Method naming conventions in interfaces ending with -able

An interface is a contract. If a class implements an interface, this means that the class fully supports all operations stated in the interface. (Although this is not always the case). Regarding the statement in the title: generally all interfaces whose names end with "-able" mark the class as being able to do something. Examples: Runnable - run(), Executable - execute(), Comparable - compareTo(), etc.

A)

public interface Openable {
void open();
}

The above interface does indeed imply that any class implementing it can be opened, irrespective of the call context. It does not necessarily mean that the object will open, but that is not the point.

Consider the following, as proposed by @sgj88_:

B)

public interface Openable {
void open(Opener opener);
}

Since you state that only Opener can open Openable objects, theoretically this is a better option. (Ideally, objects should only change their own internals not other objects'). However, in practice Opener acts like a behaviour altering object, akin to the strategy pattern.

public interface Opener {
// or something similar
double fractionToOpen();

Opener FULL_OPENER = () -> 1.0;
Opener HALF_OPENER = () -> 0.5;
}

The reason for this is that Opener does not know anything about the internals of Openable in order to change its state, while the name suggests that it does. You wouldn't have open() in Opener because then you wouldn't need Opener in the first place. Hence the semantics of design and implementation do not match.

C)

Since only Opener type can open them then it can be assumed that there are more ways to modify the state of Openable than just a single call to open().
Then, Openable needs more methods for modifying its internal state,e.g.

setOpenRate(), setOpenFraction(), etc.

If this is not the case and the question refers to the call privileges, i.e. there is just a single class Opener in which open() can be used, then it shouldn't be an interface.

Perhaps given some context in which the interface is being designed would help to identify the best option.

What is standard for Interface naming in java api

It's very common for those '-able' names to be interfaces in Java, but there is no official convention for interface naming that I've found that suggests that '-able' names should be interface names, though typically that is the case.

Official Java naming conventions can be found here - it's pretty lean, there really aren't any restrictions for class or interface naming:

  • http://www.oracle.com/technetwork/java/codeconventions-135099.html#367

As to your Throwable question, James Gosling once answered why it's a class rather than an interface, even though the name was more fitting for an interface.

Unfortunately, the original article from Sun/Oracle's site has vanished into the internet ether, so I can only provide indirect attribution:

  • http://c2.com/cgi/wiki?JavaExceptionQuestion
  • http://www.ibm.com/developerworks/forums/thread.jspa?threadID=58994&tstart=45

edit: Since I continue to get upvotes to this question, I found the link to the Sun discussion via the Wayback Machine, here: http://web.archive.org/web/20071013225816/http://java.sun.com/features/2002/03/gosling.html?source=jdc_news&date=20020430

JDC: Why is Throwable not an interface? The name kind of suggests it should have been. Being able to catch for types, that is, something like try{}catch (), instead of only classes. That would make the Java programming language much more flexible.

JG: The reason that the Throwable and the rest of those guys are not interfaces is because we decided, or I decided fairly early on. I decided that I wanted to have some state associated with every exception that gets thrown. And you can't do that with interfaces; you can only do that with classes. The state that's there is basically standard. There's a message, there's a snapshot, stuff like that that's always there. and also, if you make Throwable an interface the temptation is to assign, to make any old object be a Throwable thing. It feels stylistically that throwing general objects is probably a bad idea, that the things you want to throw really ought to be things that are intended to be exceptions that really capture the nature of the exception and what went on. They're not just general data structures.



Related Topics



Leave a reply



Submit