Java Interfaces/Implementation naming convention
Name interfaces descriptively, for instance, Cacheable. For a straightforward implementation, append Impl like CacheableImpl or be specific like RedisCache for a Redis-backed cache, making your code more intuitive and self-explanatory.
Interface:
public interface Cacheable {
    void cacheData(); // Hey there, it's time to cache!
}
Implementation:
public class CacheableImpl implements Cacheable {
    public void cacheData() { // Let's cache like there's no tomorrow! ๐ป๐๐จ
        // Basic caching
    }
}
public class RedisCache implements Cacheable {
    public void cacheData() { // Let's turn up the Redis magic! ๐ซ
        // Redis-specific caching
    }
}
Selecting Meaningful Names for Interfaces
Aim for clarity and purpose in interface names. Reflect the contract an interface defines without hints at any implementation specifics. For instance, Serializable, Iterable, and Comparable all declare an action or functionality.
Implementations: What's in a Name?
Implementations should have a name suggesting its uniqueness. A common convention is to choose a Default prefix for a common or straightforward implementation, such as DefaultService.
The Abstract Class Conundrum
An abstract class providing partial implementation should be named to hint at its abstract status without relying too heavily on prefixes. Instead of AbstractList, try ListSkeleton to suggest a template for list implementations.
Special Implementations: Make the Exception the Rule
Distinct implementations need distinct naming based on their unique traits or usage scenarios. For example:
- ๐บ Encoder๐Base64Encoder
- ๐บ Queue๐PriorityQueue
Functionality in Names, Flexibility in Design
Interface names should focus on functionality and allow flexibility in design, abstract enough to cover all potential implementations without hinting at a specific behaviour. For instance, Stream could apply to FileStream or NetworkStream.
Event Handling: A Naming Pattern
When it comes to event handling, follow the pattern established by Java's AWT package:
- ๐บ EventListener๐MouseAdapter
- ๐บ EventObject๐ActionEvent
Testability and Maintainability through Naming
Proper naming patterns augment testability and maintainability of code by making it easier to swap implementations and mock interfaces during testing, like having the PaymentProcessor interface and a MockPaymentProcessor for test scenarios.
Keeping Clutter at Bay
The Impl suffix, despite popular, should be avoided. It adds minimal contextual info and could lead to redundant and cluttered names. Additionally, it doesn't highlight differences between various interface implementations.
Was this article helpful?
