I’ve read Egypt Java Experts’ post about generics tips and even though I agree with the author’s claim that the generics feature make for a better API design, sometimes it’s just an overkill for the framework you’re designing.
I will take hplusplus’ example AbstractProtocolFactory and HttpProtocolFactory and hope s/he won’t mind. These classes were declared as:
public abstract class AbstractProtocolFactory<P extends Protocol,
C extends Configuration> { ... }
public class HttpProtocolFactory extends
AbstractProtocolFactory<HttpProtocol, HttpConfiguration> { ... }
Part of designing a good API, especially when talking about protocols and configurations, is to make it highly configurable in a post-deployment state. This is often done by using the Strategy design pattern, and can be seen in Java’s API in several occassions.
For example, if I used message digests, I would use create a MessageDigest instance using MessageDigest.getInstance(String), making sure that the String passed is retrieved from a configuration file, so I could change the digest type later.
Going back to hplusplus’ example, I couldn’t use such a thing. This is because the factory itself is generified, and in order to use it I need to provide the class types I require hard-coded. This might prove to be type-safer than using a string, but as I said before, some things need to be changed in a post-deployment state. If a year later I would decide to change the protocol type to an XML protocol instead of an HTTP protocol, I couldn’t without redeploying my application.
Another minor twist: In the example, hplusplus defines Protocol as:
public interface Protocol<C extends Configuration>
So a Protocol is defined to be used only with a certain type of Configuration. Because of this, the AbstractProtocolFactory could accidently be told to create a Protocol with a wrong type of Configuration, like HttpProtocol with XmlConfiguration. I would make a slight change like this:
public abstract class AbstractProtocolFactory<P extends Protocol<C>,
C extends Configuration> { ... }
That way, it’s type-safeer.