I am supposed to make a class that should be a container for an interval of values (like in mathematics). I have already decided that I’ll use internally a SortedSet.
One of the the things I’m supposed to implement is a method that “gets an ordered set with all the elements in the interval”.
class Interval {
private SortedSet sortedSet = new something();
...
<<method that should return an ordered set of values>>
}
My question resides in what should be both the method’s return type and name. Several hypothesis arise:
SortedSet getSortedElements();I am internally using aSortedSet, so I should return that type. I should state that intent in the method’s name.SortedSet getElements();I am internally using aSortedSet, but there’s no point in stating that in the method name(I don’t see a big point in this one).Set getElements();I should try to always return the most basic type, thus I am returning a Set. By the contract and definition of the method, people already know all the elements are in order.Set getSortedElements();For the method return type, the same as above. About the method name, you are stating clearly what this method is going to return: a set of elements that are sorted.
I’m inclined to use 4. , but the others also seem alright. Is there a clear winner? Why?
SortedSetis an interface with the contract that the elements are sorted. It also exposes some methods not available inSet(such asfirst()). If you are supposed to return an object that obeys that contract (for example, returns ordered values on iterator()), then you should return aSorted Set. If not, you should return aSet(or aCollection).You figure out what to return based on how you want the result to be used. Think what “gets an ordered set with all the elements in the interval” means first, then worry about the implementation.
By the way the code
is illegal, because
SortedSetis an interface. Since this is homework I will leave it to you to figure out why that is a problem.