I have a basic question about using the “Best Practices” in coding. (I’m using Java, but the question is general to OOP.) When writing method’s for a class that are intended to be used in the long run, is it best to leave the return object with or without generics?
To be specific in my case, I’m returning a Map<String, Integer> with the method. Should I specify this in the return statement, or should I simply return a Map?
It is best to use generics whenever possible. It will help avoid runtime exceptions, and it won’t force the people using your code to do a bunch of ugly type casting. For example, if you use the following signature:
… then the consuming code might look like this:
… but if you use a signature like this:
… the consuming code might look like this:
By using generics, not only do you save that
(Map<String, Integer>)cast, but in the event that you changegetMapto actually return aMap<String, Object>, you will get a compile-time error (which is easy to catch and fix), rather than possibly getting an exception when you callmap.get(key)and the JRE tries to do an automatic cast of some random Object into an Integer.