Today I came to a fundamental paradox of the object programming style, concrete types or interfaces.
Whats the better election for a method's return type: a concrete type or an interface?
In most cases, I tend to use concrete types as the return type for methods. because I believe that an concrete type is more flexible for further use and exposes more functionality.
The dark side of this: Coupling. The angelic one: A concrete type contains per-se the interface you would going to return initially, and extra functionality.
What's your thumb's rule?
Is there any programming principle for this?
BONUS: This is an example of what I mean ReadOnlyCollection or IEnumerable for exposing member collections?
An interface name can also be used as a return type but the returned object must implement methods of that interface. The following Java program shows the implementation of a class name as a return type.
It means, that the member function can return any implementation. This follows the "Program to an interface, not an implementation." design pattern. Follow this answer to receive notifications.
A concrete class is a class that has an implementation for all of its methods. They cannot have any unimplemented methods. It can also extend an abstract class or implement an interface as long as it implements all their methods. It is a complete class and can be instantiated.
A concrete class can implement multiple interfaces, but can only inherit from one parent class.
My rules of thumb:
1) Initially, I have the method return the interface type, because its always easy to change it to the concrete type later if necessary. Harder to go back the other way.
2) Even if the method is declared to return the concrete type, I would code the callers to use the interface type whenever possible:InterfaceType i = xyz.methodThatReturnsConcreteType();
.
3) Whether I own the calling code makes a difference too (internal vs public APIs):
Other considerations:
In summary,
Rule of thumb, in return types, be a as specific as possible, in parameter types be as unspecific as possible. Also prefer interfaces, since you may later exchange your implementation if necesary, without changing the clients of your API.
Interesting question. I believe you have to ask yourself how can the return data be used. Using the age old car analogy if you had
public AccelerationResponse PressAccelerator(float force) {}
Chances are that you'd want to return an interface rather than a class. You could be interpreting this response differently depending on certain conditions.
If you are guaranteed that your return can only be used in the manner expected by the concrete implementation then using that class makes sense. I'm not sure of any widely accepted principle but my rule of thumb is if the return type can be reused in different implementations an interface makes more sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With