Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Some time ago I read a kind of "rule of thumb" about the concreteness of method parameter types, return types and property types, but I just do not remember it.

It said something about keep your return types as concrete as possible and your parameter types as abstract as possible... or vice versa.

I don't know if it was actually a good or bad advice, so if you have your own thoughts about it, please let a comment.

Cheers.

share|improve this question

3 Answers 3

up vote 5 down vote accepted

Require no more, promise no less.

The phrase comes out of "Design by Contract" ideas pioneered by Bertrand Meyer.

http://wiki3.cosc.canterbury.ac.nz/index.php/Design_by_contract

Also see the "Liskov substitution principle"

http://stackoverflow.com/questions/56860/what-is-the-liskov-substitution-principle

share|improve this answer

Having abstract inputs and concrete outputs makes your function more general. This means it can be used in more ways. On the other hand it puts stronger constraints of your method, limiting how future implementations of it might work. So it's a trade-off between different goals.

share|improve this answer

It could be you heard an extrapolation of Postel's law: "Be conservative in what you send, liberal in what you accept."

Mostly it's about maximizing code reusability. It's easy to come up with cases to demonstrate why it helps. Consider Java's Iterable<T> as an example. If the only thing your method does is iterate through all the Ts, having an Iterable<T> as your parameter type allows you to use that method with over 60 built-in classes, not to mention any custom classes that implement the interface. If you limited it to, say, Vector<T>, then any code that calls your method would have to convert to a Vector<T> first.

On the other hand, returning an Iterable<T> from a method limits the amount of code that can use your return value to those that take an Iterable<T> parameter. If you return a very concrete type, like Vector<T>, then your return value can be passed into any method that takes a Serializable, Cloneable, Iterable<T>, Collection<T>, List<T>, RandomAccess, Vector<T>, AbstractList<T>, or AbstractCollection<T>, and it will work as expected.

share|improve this answer
    
Postel's law is pretty high on my list of "biggest software engineering mistakes". –  CodesInChaos Feb 27 '13 at 20:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.