Java Interface Naming Conventions [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I work on a Java web-app that uses Spring for dependency injection and JMock for mocking out these dependencies in our unit tests.
Currently our team is at a point were we have a few different opinions in terms of how to name certain interfaces that we use. We have no issue with naming the interfaces in our domain that have multiple implementations, that is simple. However, when it comes to interfaces for which we only have one implementation and intend on only having one implementation in the future, we have hit a snag.
The reason that we have such interfaces is purely for mocking, for example, we have services and repositories that we mock out in our unit tests and these services will be named "DocumentMappingService" or for repositories "EmployeeRepository". At the moment some of the guys just prefix the associated interface name with an "I", i.e. "IDocumentMappingService" and "IEmployeeRepository". Others name the interface as I have above and then append an "Impl" after the interface name for the implementing class.
The third "faction" feels that both of these options are poor. Looking at literature such as the well-known "Growing object-oriented software, guided by tests" would lead one to believe that both of the before-mentioned options are poor and that the interface name should clearly define the contract and the implementing classes name should clearly specify how that contract has been implemented. We have found this quite difficult to do in the case I have mentioned above though.
I was hoping that someone out there has had a similar issue before and has some suggestions ito which option is the best and why. Also, if you think that the "I" and "Impl" options are both poor, then please suggest a specific alternative convention.

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

An answer to such a question can only reflect the tastes of the person who answers... So these are my tastes:
I hate the initial I. It brings nothing of value to the picture. It reminds me of the Hungarian notation where float variables were to be suffixed with _f or the like. No.
The Impl suffix is good enough. But on the other hand, it sounds weird.
I'd suggest two alternate proposals for a given interface Foo:
create a single implementation but not with the Impl suffix; find a more "appealing" name. For instance, TheOnlyOneFoo;
create a factory with an appended s: Foos. Then, a Foo instance would be a Foos.newInstance(whatever, args).
I prefer the second solution, for two reasons:
it can hide the fact that the real implementation has an ugly name;
it can be extended easily when you realize one day that "no, after all, there is more than one implementation for that": just add another static factory method; and if the only existing method in existence sounds too generic, you can just mark it as #Deprecated.
It could even be used in a manner so that all Foo implementations are package local, or even private to the factory. But stack traces would look worse...
No real solution there ;)
edit: as for mocking:
I'd recommend mockito. Really. It is very easy to use, and very powerful.
If those are "one-implementation classes" you are dealing with, maybe there is a better alternative in the JDK itself? What is it that you want to do exactly? The JDK has hidden treasures...
And as a final note... Have you considered the builder pattern?

Related

in which scenario abstract class and interface should not be used? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have been asked in interview in which scenario abstract class and interface both should not be used ?
I wasn’t able to clearly answer his question with specific examples of when you would not want to do this, at the time. I have search lot for specific answer with example but unable to find.
I know when to use which one. Also I understand that
abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.
So can I answer that when I don't found any relation then i should not use it.
Can you genious guys spend a minute and answer me to increase my knowledge?
Thanks in advance.
One anti-pattern that comes to mind is where constants (as public static final variables) are put on either an abstract class and an interface, and then the users of these constants implement the interface or extend the abstract class. The so-called advantage of this was that the constants did not need to be qualified every time they were used. e.g. MyConstants.MY_VALUE vs MY_VALUE
With Java 1.5 and later, static imports can now be used to avoid having to qualify the constant with a class name. Though personally I don't really mind qualifying constants with a class name especially if the constants' class names have a meaningful 'grouping' name.
Perhaps when you explicitly want just one implementation, so that you don't maintain two versions of the same thing. One might also make the class final in this situation.
I have one idea. Probably if your class contains a set of static utilities. For example StringUtils. But anyway I think that the question as you wrote it does not have too much sense.
2 cases I think
1 : if you have to instantiate objects of your class (eg: MyClass object=new MyClass())
2 : in case of inheritance of the same implementation as the parent class eg:
class Parent {
int x;
public void setX(int x) {
this.x = 2 * x;
}
}
class Child extends Parent {
int y = 1;
public void setX_AND_Y(int x, int y) {
setX(x); // same implmentaion
this.y = y;
}
}
I had some issues with spring bean that had to implement interface and extend some base class in the past.
This was rather an advanced problem related to AOP and Spring, so I cannot be 100% sure that this is what your interviewer asked, but it is totally something you can stumble upon in the wild, and not limited only to Spring.
Often you want to add AOP to your Spring application (for example to use #Transactional annotations). The problem is that there are couple of ways how AOP can be implemented, from patching bytecode at compile time or loadtime, to generation something similar to wrappers at runtime.
The latter approach is the most cheap, build-structure-wise, and used more commonly than others but it has it's disadvantages.
One of them is that there are plenty of ways to do this and approach differ from what exact bean (class instance) you want to weave (wrap). Thing like "whether class implements interface", "whether class extends class" and combinations matter here.
I won't delve deep into details here, simply because I struggled with this pretty while ago, but you can get a grasp of what you'll have to deal with from spring docs briefly discussing this matter.
I will say though that in my project things went wrong when I decided to add class that extended another class and implement some interface. It was quite a challenge to make things work, because you have to have really decent understanding of how Spring itself and AOP weaving techniques work and how to configure all these things so they work as expected.
UPDATE: Answering your question in one sentence: You probably do not want to extend abstract class and implement interface at the same time in the code that deals with dynamic class proxying/AOP/code generation.

Dependency Injection - Proper use of interfaces? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been reading about DI and best practices, and still haven't found the answer to this question. When should I use interfaces?
Some developers suggest to add interface for every object that is being injected. This would make a modular application.
Some other are against this.
So my question is which one is correct?
EDIT:
Below are the two sides, I still don't see the advantage of using interfaces. In both cases I can easily mock classes, and change the implementations
Using interfaces
bind(IUserStorage.class).to(UserStorage.class);
// Unit test
bind(IUserStorage.class).to(Mock(UserStorage.class));
Not using interfaces
bind(UserStorage.class).to(UserStorage.class);
// Unit test
bind(UserStorage.class).to(Mock(UserStorage.class));
I can't believe using interfaces is againt OOP principles!
I would definitely use interfaces in this scenario. It means you're loosely coupling your components and can easy mock and/or substitute alternatives. Lots of DI frameworks will use the interfaces in order to provide additional functionality (e.g. create proxy objects mapped to the real objects, but with additional features).
As such I would try and use interfaces for all but the most trivial of injected objects. At some stage you're going to want to make use of substitutability, framework code generation etc. and retrofitting interface usage is an additional pain that it's easy to avoid at the beginning of a project.
Interface based design is the cornerstone of IoC, here is a short description of Interface-based design (Sorry that I'm referencing my own blog, but I just finished an article about this, it was an extract from my MS Thesis):
Nandigam et al. defines Interface-based design as "a way of developing
object-oriented systems where one consciously and proactively defines
and uses interfaces wherever possible in a design to reap the benefits
of designing with interfaces" [Nan09]. Applications with an
interface-based design follow the principle "program to an interface,
not an implementation". This principle brings the following benefits
to the resulting system [Dav03]: flexibility (describes the system
robustness to change), extensibility (the ease with which a system may
accommodate additions) and pluggability (the ability that allows
substitutions of objects with identical interfaces at run-time).
Once you mix interface design with IoC you obtain the following benefits:
Tasks are decoupled from the implementation.
Increases modularity where modules rely on other modules solely on their contracts (interfaces).
Increases pluggability and replacing a module does not have a cascading effect on other modules.
To answer your question, I would use interfaces for different types of modules. For example, one per service or repository.
I do not create interfaces for controllers or Model classes (MVC apps).
All this, as a side effect, facilitates testing.
If you use interfaces or at least abstract/inheritable classes you can change the behaviour of the program by an easy exchange of the implementation (inject another class) in the DI/IoC config.
Using interfaces is a good practice (imho). This is especially very important if you are writing UnitTests which needs mocks. It is much harder to write UnitTests with a good coverage (not to say impossible in most "real world" cases) if you're not using interfaces.
I think you should use an interface if there might be a chance that the injected part could change. It should be easy to extend your implementation, see Open-Closed-Principle. => This will require the exchange of modules/parts/implementations... ask yourself what would happen if your class has no virtual functions to override and you are forced to change the implementation.
I would use interfaces at least for the public classes / parts of your code (the parts other programmers would use).
Having a look at your sample. The problem is at the wiring part and not only the binding of a class as (default) implementation of an interface (binding works, but wiring could break).
For example if you have 2 implementations (C# sample here, should be the same in Java etc., too):
public interface IUserStorage
{
void Write(object something);
}
public class UserStorageTextFile : IUserStorage
{
public void Write(object something) { ... }; // stores to text file
}
public class UserStorageDB : IUserStorage
{
public void Write(object something) { ... }; // stores to DB
}
public class MyStorageClient
{
public MyStorageClient(IUserStorage storage) { ... } // copy to private field and use it etc.
}
Depending on your IoC it should be easy to wire
an instance of MyStorageClient to your binding of IUserStorage.
bind(IUserStorage.class).to(UserStorageDB.class); // Java sample, eh?
But if your MyStorageClient is strongly forced to use DB already...
public class MyStorageClient
{
public MyStorageClient(UserStorageDB storage) { ... } // copy to private field and use it etc.
}
... it is imposible to wire it up with the UserStorageTextFile class except the UserStorageTextFile is inherited from UserStorageDB... but why should you have a dependency to e.g. Oracle drivers (required by UserStorageDB) if you only want to write a simple text file?
I think the sample is clear enough and shows up the benefits of using interfaces...
but if not... try to do this:
bind(UserStorageDB.class).to(UserStorageTextFile.class);
// and in another config/module/unitTest
bind(UserStorageTextFile.class).to(Mock(UserStorageDB.class));
// and try to wire it against your client class, too (both ways, meaning one config for TextFile and load a config for the DB after changing only the configuration)
Your question states "some developers [are for this]" and "some developers [are against this]", so there is no right answer. But this is why I agree that interfaces are overused
If you are creating a library, choosing when to use interfaces is important. It is harder to create a maintainable contract when you don't control how your code is consumed.
If, however, you are creating an application, it less likely to require an interface, because the public interface of a class can serve as the maintainable contract to consuming code. Let's say version 1 looks like this:
public class UserStorage
{
public void Store(User user) { /* ... */ }
}
You don't even need refactoring tools to change it to this:
public interface UserStorage
{
public void Store(User user);
}
class TheImplementation implements IUserStorage
{
public void Store(User user) { /* ... */ }
}
Then you can easily use refactoring tools to rename the interface to IUserStorage.
So when you are writing non-library code, you can usually get away with a class until you need swappable implementations, decorators, etc. You should use an interface when the public interface of the class does not suit your needs. (For example, see the interface segregation principle)
In short - having an interface that is 1:1 with a class is unnecessary indirection in application code.

Why not singleton instance provided out of box in java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
You can make class singleton by implementing Singleton pattern. Nowadays singleton class is basic requirement.
Why don't JVM handles Singleton object creation by itself at runtime?
By having marker interface like "Singleton" and creating object instance once by JVM at runtime. Anyways Java compiler adds "extends Object" if Class is not extending any other class. Similar approach can be applied in Singleton case.
This will save lot of time and development effort and discussions around various implementations of Singleton pattern.
1) Synchronized getInstance()
2) Synchronized block inside getInstance() instead of making whole method synchronized
3) Option 2 with singleInstance as volatile member
This will also save lot of time and duplicate efforts if you need to implement singleton pattern in multiple classes(not considering SingletonPatternFactory class which will return singleton instance of any class which is been passed)
Let's take a look at all of the steps needed to create a singleton:
private constructor
a static final field
(optional) if you want the class to be serializable, trivial implementations of readResolve and writeObject
Most singletons that I've come across don't care about serialization, so that third step isn't needed. This leaves you two really, really easy steps.
public class Whatever extends WhateverElse {
public static final Whatever INSTANCE = new Whatever();
private Whatever() {}
}
It's even lazy-loaded, since the constructor won't be run until you access the class, which would only be to get the singleton instance of it. I don't know what your definition of "a lot" is as far as time and development effort, but I don't consider this to be onerous.
Implementing basic design patterns is not the responsibility of the core language, unless there is a compelling reason it should be. Design patterns come and go -- for example, the singleton pattern is widely regarded as an extremely bad pattern that should never be used. Even if you decide to use it anyway, do you want an eager singleton? Lazy singleton? What should happen if instantiation fails for some reason? There's a whole lot of seemingly minor issues to cover, but adding this feature to the language is not a trivial change.
By implementing it yourself you get exactly the features and behavior you want.
You can use an enum instead of a singleton pattern - this is not very complex:
public enum Singleton {
INSTANCE;
}
There are two basic categories of Singletons, those with lazy initialization and those with eager initialization.
Aside from the whole argument on flavors of Singletons, many Java developers consider Singletons to be bad or an anti-pattern. This is probably an area of disagreement among those currently maintaining the Java spec.
Lastly, the same could be said true of most any pattern. There is not a huge need for a language to adopt or endorse any specific set of patterns, IMHO.
You would not want a Singleton interface, since the interface has no behavior of its own. You would want an abstract class... kind of. In reality you would want something a lot more powerful than just an abstract parent. You need to have a private constructor (or a private instantiation method that calls a private constructor and returns the single instance) that has to be called in the getInstance() method defined in the parent (violation of scoping).
What you are suggesting is something that will work outside of the traditional class system. Perhaps it can be done as a new object type (similar to how an enum is not a class), but definitely not as a standard interface or class.

Java packages for interfaces, abstract classes and implementations [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Ahoi!
Even though I only have a small number of classes, I'd like to hear your suggestions about packages.
I do have an GenericDAO interface, an abstract GenericHibernateDAO class, an UserDAO interface and finally a UserDAOHibernate class. They're roughly sorted by how general they are.
I'll certainly add more interfaces like UserDAO and UserDAOHibernate, so they will need their own package.
I also have a GenericEntity interface, an abstract LongEntity class (which needs a better name btw.) and the User class. I'll add more classes like the User class lateron.
How many packages would you recommend and which names would you use?
I recommend using 50 billion packages. Each class shall have its own package, but every package shall not have a class. And packages shall share the name of their class. And for those packages without a class, they shall be named by simply closing your eyes and slamming the keyboard.
The packages your create depends on some factors. For example, if your API makes use of package-private scoping, you might arrange them differently than if the API is more open.
You can create a package like
com.company.app.domain
for your entities (you can also have model, entity, or anything else that makes sense, instead of domain, for your app)
You can create
com.company.app.dao
for your Daos.
If you want to restrict how your model objects talk to each other, you could create a package for each type (like User), with the DAO and services in the package. Or you can alternatively create a .user.service package.
Without knowing your application design, I can't really say more, other than don't create a complicated package hierarchy if you don't need it.
Packaging classes and interfaces is an interesting topic. Some people are in the camp of: "Class and class function visibility determine packaging" whereas others are in the camp of: "Package classes and interfaces based on functionality.
Personally, I do the latter. In my book, packaging restrictions based on class/function visibility is a design issue.
For your example, I only see two:
what.ever.generic
what.ever.user
Sounds too complicated to me. (Yes, I read your previous question.)
I don't see why you have UserDAOHibernate when you have a generic DAO.
I'd do it this way:
package persistence;
public interface GenericDao<K extends Serializable, V> {
List<V> find();
V find(K key);
K save(V value);
void update(V value);
void delete(V value);
}
I'd have a Hibernate implementation for this, but an instance for user would look like this:
GenericDaoImpl<Long, User> userDao = new GenericDaoImpl<Long, User>();
All that stuff about Entity is overkill in my opinion.
I would definitely group classes by function and not by visibility or any implementation detail:
Implementation changes (function should not), but do you want to move your classes to another package in that case?
For classes, no-one ever asks Should I put all String/Integer/Collection variables in a separate class? But people seem to struggle more with package organization.
Use something to inject the implementations into your objects. Use the interfaces as the private member types.
class MyObject
{
private GenericDao meaningfulName;
private UserDao meaningfulName;
}
blah.dao - DAO interfaces here.
blah.dao.hibernate - Hibernate implementation of DAO interfaces here.
blah.entity - GenericEntity here. Abstract (i.e. base) implementations of
interfaces here (LongEntity for example).
blah.entity.impl - Implementation of GenericEntity here.
blah.domain - Domain classes like User here.
Instead of LongEntity maybe use BaseEntity.

Interface naming in Java [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
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:
Class = User, Interface = UserInterface
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?"
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!
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
There may be several reasons Java does not generally use the IUser convention.
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.
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.
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.
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.
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.
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.
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.
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.
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.
=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.
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.

Categories