Interface naming in Java [closed]
Asked Answered
A

11

371

Most OO languages prefix their interface names with a capital I, why does Java not do this? What was the rationale for not following this convention?

To demonstrate what I mean, if I wanted to have a User interface and a User implementation I'd have two choices in Java:

  1. Class = User, Interface = UserInterface
  2. Class = UserImpl, Interface = User

Where in most languages:

Class = User, Interface = IUser

Now, you might argue that you could always pick a most descriptive name for the user implementation and the problem goes away, but Java's pushing a POJO approach to things and most IOC containers use DynamicProxies extensively. These two things together mean that you'll have lots of interfaces with a single POJO implementation.

So, I guess my question boils down to: "Is it worth following the broader Interface naming convention especially in light of where Java Frameworks seem to be heading?"

Anett answered 12/2, 2009 at 15:51 Comment(13)
"Where in most languages"? Which languages besides the .Net ones?Swatch
Not all the .NET ones either; C++ is a usable .NET language, and doesn't have interfaces per se (abstract base classes can come with some implementation). Does this question boil down to "Why isn't Java like C#?"?Plasticity
Nope, question is java based, but it's really a question regarding interface naming conventions, and why some languages choose to do things in certain ways.Anett
Different language communities have different naming conventions, and this has been true for a long, long time. Finding out how the naming conventions originated is sometimes essentially folklore research.Plasticity
Eclipse is a significant outlier that uses Java with IFoo style naming. wiki.eclipse.org/Naming_ConventionsDiorio
Besides .NET, Adobe Flash/Flex also uses the IFoo naming convention.Similar
Before the .NET ones, it was common use to name COM interfaces with an I prefix, e.g. IUnknown, IStream. In C++, it was common to have IStream* and the like when interfacing to COM. It seems like a natural extension of the C- prefix for classes, though I find it interesting that .NET has abandoned class prefixes. Delphi used the same convention for both its own interfaces as well as its use of COM interfaces. Personally, I don't mind the convention. The OP's question here indicates some of the frustration with Java interface-naming conventions; I wish a standard had been set.Guarantee
If you take a look at names of Interfaces in Android SDK (Java as well), you will see that they used convention of having word Interface on the end of an interface name, like NetworkInterface, DialogInterface, etc.Fossorial
How can this question be "closed as not constructive" when it's so popular and of interest to so many people?Bennington
Because it has no correct answer. I asked it before SO was as strict about the kinds of questions it accepts.Anett
I respect that you, yourself, finds value in the question being closed. However, it's actually an answerable question if it's re-worded. Also, even though it's closed it's being allowed to be used to mark other (possibly better worded) non-closed-questions as duplicates. That just doesn't make sense. Based on the Java libraries, if they were to follow their own convention, it'd be Interface[yourInterfaceName]; based on Abstract....Ramiah
The best advice I have found so far regarding the naming convention of class and interface is that - "Interface names should always be an adjective (wherever possible) describing the enforced behaviors of the class (noun)!" as mentioned here - iwombat.com/standards/…Merline
@DavidLeonard Thats probably why Eclipse is a doomed product ;)Potted
S
369

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!

Shennashensi answered 12/2, 2009 at 16:23 Comment(14)
Totally agree. One more key to type if you use autocompletion. Lots of files starting with an I.Liquorice
Any decent IDE makes changing the code in the way you're describing easy. Also, When changing from an abstract class to an interface I'm pretty sure your clients will need to recompile anyway.Anett
Super late here, but: It doesn't matter at all if an IDE makes changing the name of something easy. Code using an instance of some type should never, ever care if that type is an interface or a class or what. As such, exposing such a detail in the name of the type is pointless and harmful to understanding. The type and the contract it exposes are what matters!Ringed
@Allain Lalonde This is only true if you have both the interface and all the clients under your control, which often is not the case.Shennashensi
Besides, if you are going the route of IFoo, shouldn't it be CFoo for the implementation and of course on failure a method would throw an EFoo.Forceful
"The prefix hurts readability" is purely subjective. As are most naming conventions. It matters more that your team settles on agreement about what to do so that the code base is consistent.Contractor
"...abstract class to an interface ... prefix I implies renaming all the occurrences of the class" - why is this bad? Aside from the fact tools make it trivial to rename something, changing something from an abstract class to an interface is a significant change (if nothing else, it's a change from "implements" to "extends").Aureus
@AllainLalonde Still while the operation is eay, you would have to commit an abuncande of files which may cause confusion. Large commits are inherently a bad thing.Freitas
@AllainLalonde, some bytecode manipulation tools need the full qualified name of a type in string form to find it in the classpath. Think about renaming all of those references with an IDE.Esau
I personally like the C#'s approach with IInterface and OtherTypes (and honestly would have been just as fine with a proper sigil). I find that this consistency helps readability over all. Changing from a Type to an Interface and vice-versa is a source breaking change in both Java and C# - this completely negates the point of "renaming occurrences". A good IDE such as ReSharper can help you make this change safely and trivially through the source-code base.Triserial
Eclipse: "For interface names, we follow the "I"-for-interface convention: all interface names are prefixed with an "I". For example, "IWorkspace" or "IIndex". This convention aids code readability by making interface names more readily recognizable."Motive
"The prefix hurts readability." so what about names in string.xml ? like STR_CLOSE, STR_OK...Bethina
@YoushaAleayoub - that is a tautology just like the I prefix, useless duplication of information the public interface XXX tells you it is an Interface. Same with hungarian notation which is not needed with modern languages that are not C and not even with C anymore with a decent IDE that can tell you the types when you hover over a variable.Fukuoka
From wiki.eclipse.org/Naming_Conventions "For interface names, we follow the "I"-for-interface convention: all interface names are prefixed with an "I". For example, "IWorkspace" or "IIndex". This convention aids code readability by making interface names more readily recognizable."Eulalia
E
136

Is there really a difference between:

class User implements IUser

and

class UserImpl implements User

if all we're talking about is naming conventions?

Personally I prefer NOT preceding the interface with I as I want to be coding to the interface and I consider that to be more important in terms of the naming convention. If you call the interface IUser then every consumer of that class needs to know its an IUser. If you call the class UserImpl then only the class and your DI container know about the Impl part and the consumers just know they're working with a User.

Then again, the times I've been forced to use Impl because a better name doesn't present itself have been few and far between because the implementation gets named according to the implementation because that's where it's important, e.g.

class DbBasedAccountDAO implements AccountDAO
class InMemoryAccountDAO implements AccountDAO
Eduardo answered 12/2, 2009 at 16:5 Comment(8)
I think you'd want to know its a DAO since that describes the general functionality without needing to open the class. If I'm looking through the class files in a project its easy to see all the DAOs by looking for *DAOTittletattle
DAO is a well known pattern for database access, so having the pattern in the name makes it easy to know what the class does just by looking at its name. P.S. It would be better to follow the camel notation strictly ("AccountDao") such as in mina.apache.org/changes-between-2x-and-1x.htmlStaw
@marker, it's not like having an I to indicate an interface. DAO tells you that the class or interface is an object for accessing account data, which is what the object does. Having an I tells you its an interface, which has nothing to do with the object itself but semantics of the languageEduardo
As you present it, its prefix vs suffix.Jaqitsch
@Andrei: Nope, it's semantics ("DAO") vs. unecessary decoration of a language artifact ("I" as in interface; a fact, which is mentioned in the code anyway "interface IFoo...")Thumbscrew
Interesting reading: interface and class naming anti-patterns.Frau
Isn't that pretty much what I said up there?Eduardo
a semantic way naming the implementation & interface, can't be more agreed with youBerkshire
S
83

There may be several reasons Java does not generally use the IUser convention.

  1. Part of the Object-Oriented approach is that you should not have to know whether the client is using an interface or an implementation class. So, even List is an interface and String is an actual class, a method might be passed both of them - it doesn't make sense to visually distinguish the interfaces.

  2. In general, we will actually prefer the use of interfaces in client code (prefer List to ArrayList, for instance). So it doesn't make sense to make the interfaces stand out as exceptions.

  3. The Java naming convention prefers longer names with actual meanings to Hungarian-style prefixes. So that code will be as readable as possible: a List represents a list, and a User represents a user - not an IUser.

Stoneblind answered 12/2, 2009 at 16:17 Comment(0)
A
82

There is also another convention, used by many open source projects including Spring.

interface User {
}

class DefaultUser implements User {
}

class AnotherClassOfUser implements User {
}

I personally do not like the "I" prefix for the simple reason that its an optional convention. So if I adopt this does IIOPConnection mean an interface for IOPConnection? What if the class does not have the "I" prefix, do I then know its not an interface..the answer here is no, because conventions are not always followed, and policing them will create more work that the convention itself saves.

Aboutface answered 12/2, 2009 at 16:15 Comment(1)
I like this, since it also helps get you in the mode of using interfaces for external dependancies rather then coupling the classes.Tel
C
55

As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:

class Number implements Comparable{...}  
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}

Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.

Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?

I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.

Concession answered 25/5, 2010 at 3:44 Comment(2)
I think the examples you provide to support "interfaces as adjectives" is skewed, since those interfaces are intended to be more like mix-ins (or traits). Thus, interfaces are good for both adjectives and nouns - but probably not for indefinite transitive verbs 8^PKendry
This might be changed in the last years. The oracle docu. allows interfaces as types: [link] docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.htmlLaudatory
W
44

Bob Lee said once in a presentation:

whats the point of an interface if you have only one implementation.

so, you start off with one implementation i.e. without an interface. later on you decide, well, there is a need for an interface here, so you convert your class to an interface.

then it becomes obvious: your original class was called User. your interface is now called User. maybe you have a UserProdImpl and a UserTestImpl. if you designed your application well, every class (except the ones that instantiate User) will be unchanged and will not notice that suddenly they get passed an interface.

so it gets clear -> Interface User implementation UserImpl.

Wynn answered 12/2, 2009 at 16:18 Comment(12)
Using interfaces helps will Test Driven Development. We've run into numerous issues with out Domain Model and testing because we decided NOT to use interfaces. A friend of mine once quoted: "Everything is an interface, it will save you in the long run."Fray
if you use EasyMock, there is no real use for an extra interface. if you dont use something like EM, yes, than you will need an interface for every class that is need as a dependency in a class that needs to be tested. -> so you will have more than one impl (test+real)Wynn
Mocking and easy proxy support. I'm sure there are other reasons to provide interfaces as well.Jurel
As I recently said to a colleague, it costs nothing to introduce an interface now but can save you plenty of time later on.Eduardo
If you might have other implementations in near-medium future, an interface would be a plus.Sarsenet
If you might have other implementations in near-medium future, an interface would be a plus. Having the interface makes the contract clear, while doing the implementation already you can easily slip a public method which you might not want there. As well, whereas this shouldn't be the decisive reason, using interfaces helps with spliting the tasks in teams with multiple developers. E.g. someone is working on a class using that implementation, while you do the implementation of it.Sarsenet
I'm intrigued about what naming convention TDD'ers use when they have an interface with only one (production) implementation; worth a question of its own, I wonder ... ?Novotny
Telling me a type is an interface violates my right as a client to not know or care what it is. If I need a Foo give me a Foo. I'll talk to Foo but don't ask me to remember what Foo is. I don't know. I don't want to know. So don't confuse me by giving me IFoo.Lully
I don't like the "I might need another impl in future" argument. I prefer a YAGNI approach: don't plan for things that haven't happened yet.Ilia
Modern mocking frameworks don't need interfaces - they can mock and spy on concrete objectsIlia
interfaces are meant to be strategically placed to points where you anticipate change. Each interface is a tradeoff of ability to be free of the compile time dependency for at least one pointer of runtime dispatch overhead. In most cases they are unnecessary, but if you do not place them where you anticipate change you can easily put your program in a state where a complete rewrite is required to meet new requirements(due to heavy coupling to undesirable non interfaced dependencies, common culprits being frameworks and io channels(eg databases)).Carrero
There are a millions reasons to have only one implementation. Only one word is enough to describe them all: ABSTRACTIONScrouge
T
25

In C# it is

public class AdminForumUser : UserBase, IUser

Java would say

public class AdminForumUser extends User implements ForumUserInterface

Because of that, I don't think conventions are nearly as important in java for interfaces, since there is an explicit difference between inheritance and interface implementation. I would say just choose any naming convention you would like, as long as you are consistant and use something to show people that these are interfaces. Haven't done java in a few years, but all interfaces would just be in their own directory, and that was the convention. Never really had any issues with it.

Tel answered 12/2, 2009 at 16:26 Comment(3)
Maybe I'm bad Java coder, but I prefer C# style, means all interfaces begin with 'I' prefix :)Manage
I'm not sure where you and others are getting this supposed convention from. It's not evident in the Java libraries...Ramiah
While this is true, the problem becomes differentiating between interfaces and classes inside methods (for example). i.e. public void AddUser(IClient client, User user). In this example you can tell that the client is an interface and the user is a class.Collimate
L
8

In my experience, the "I" convention applies to interfaces that are intended to provide a contract to a class, particularly when the interface itself is not an abstract notion of the class.

For example, in your case, I'd only expect to see IUser if the only user you ever intend to have is User. If you plan to have different types of users - NoviceUser, ExpertUser, etc. - I would expect to see a User interface (and, perhaps, an AbstractUser class that implements some common functionality, like get/setName()).

I would also expect interfaces that define capabilities - Comparable, Iterable, etc. - to be named like that, and not like IComparable or IIterable.

Langlauf answered 12/2, 2009 at 16:6 Comment(2)
If the only user you ever intend to have is User, why not just use User instead of the interface?Dentifrice
In some client/server architectures, the client side needs to know the interfaces without needing the heavyweight server implementations.Langlauf
R
6

Following good OO principles, your code should (as far as practical/possible) depend on abstractions rather than concrete classes. For example, it is generally better to write a method like this:

public void doSomething(Collection someStuff) {
    ...
}

than this:

public void doSomething(Vector someStuff) {
    ...
}

If you follow this idea, then I maintain that your code will be more readable if you give interfaces names like "User" and "BankAccount" (for example), rather than "IUser", "UserInterface", or other variations.

The only bits of code that should care about the actual concrete classes are the places where the concrete classes are constructed. Everything else should be written using the interfaces.

If you do this, then the "ugly" concrete class names like "UserImpl" should be safely hidden from the rest of the code, which can merrily go on using the "nice" interface names.

Rillis answered 12/2, 2009 at 22:18 Comment(1)
But why bother making a matching interface for every class in your program when you only need interfaces for one or two things?Chervonets
S
3

=v= The "I" prefix is also used in the Wicket framework, where I got used to it quickly. In general, I welcome any convention that shortens cumbersome Java classnames. It is a hassle, though, that everything is alphabetized under "I" in the directories and in the Javadoc.

Wicket coding practice is similar to Swing, in that many control/widget instances are constructed as anonymous inner classes with inline method declarations. Annoyingly, it differs 180° from Swing in that Swing uses a prefix ("J") for the implementing classes.

The "Impl" suffix is a mangly abbreviation and doesn't internationalize well. If only we'd at least gone with "Imp" it would be cuter (and shorter). "Impl" is used for IOC, especially Spring, so we're sort of stuck with it for now. It gets a bit schizo following 3 different conventions in three different parts of one codebase, though.

Sexless answered 13/6, 2011 at 20:57 Comment(0)
P
0

Is this a broader naming convention in any real sense? I'm more on the C++ side, and not really up on Java and descendants. How many language communities use the I convention?

If you have a language-independent shop standard naming convention here, use it. If not, go with the language naming convention.

Plasticity answered 12/2, 2009 at 17:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.