Interfaces and Implementations

Consider a Java interface and class: Dog and DefaultDog. Which of these two conventions is best?

Option 1 : Dog

Name the interface Dog and call the implementation something like DefaultDog or DogImpl.

Option 2 : IDog

Name the interface IDog and call the implementation Dog, DefaultDog, or whatever else you can come up with.

The Answer

I prefer option 1 for these reasons:

  • A vast majority of your code will utilize the interface, rather than the implementation. Thus, it’s best to keep the interface name clean, and reserve the weird names for the implementation classes, which you hardly ever see.
  • Prefixing names with “I” feels like Hungarian notation. The name redundantly specifies what the interface keyword already specifies. Should we also adopt notations for things that are static, final, abstract, etc? I think not.
  • Many interfaces will have multiple implementations. Thus, each implementation will need a different name. I see no need to also put some name discriminator on the interface.

Regarding names like “Impl” and “Default”, I prefer to avoid those when possible. For example, ArrayList and LinkedList are far better names than DefaultList or ListImpl.

Leave a Reply

Your email address will not be published. Required fields are marked *