93. General advice for interfaces
Groovy interfaces don’t allow default methods
Java interfaces allow you to provide implementation for a method. Such methods are referred to as “default methods” as any implementing class doesn’t have to provide their own implementation. This might be helpful when an interface needs to be updated/improved as it saves having to go through an existing codebase and providing the implementation. However, it’s also a bit of a trap as that approach “wedges” in functionality that may not really fit the implementing classes (and their subclasses).
Groovy’s traits gives you a neater approach to this.
The constant interface antipattern
In my earlier examples I omitted the fact that you can declare constants in an interface. At first glance this might sound like I’ve denied a useful piece of functionality but, in reality, the declaration of constants inside an interface isn’t a good idea. Consider the following example:
interface SocialNetwork {
static final MAX_FRIENDS = 100
Member friend(Member friend)
Member unFriend(Member enemy)
}
The example above provides a strong example as to how this is a bad idea as MAX_FRIENDS really is an implementation detail
and, furthermore, the interface construct doesn’t let us actually enforce the logic. The SocialNetwork interface
relies on implementing classes to make the link.
If you focus your interfaces on providing method signatures, your code will be easier to maintain. When you need to define constants, consider the following alternatives:
- For enumerated constants, definitely use an enum
- If the constant is part of a class’s logic, declare the constant with the class
- Consider creating a utility class that defines general constants of use in your program