简体   繁体   中英

naming methods with different return types but the same functionality

I'm talking about Java, but the concept would apply to other languages --

We have two methods on the same class that will have the same basic functionality, but provide different return types. Both methods will get you all the things, but one gets an iterable which can provide access to all things, and one gets a collection which includes all things.

We know you cannot do this (because it won't compile):

Iterable getThings()

Collection getThings() 

So, does anyone have thoughts about how to name the methods? It seems an easy fix to say:

Iterable getIterableOfThings

Collection getCollectionOfThings

However, this is obviously somewhat verbose and perhaps not the best solution. Does the question I'm asking imply that our organization/coding approach is somehow off the mark, or is this a valid question?

Has anyone else dealt with this scenario?

How about:

Iterable getIterator();
Collection getThings();

Iterable is a superinterface of Collection. Generally speaking you shouldn't need to do this.

Nonetheless, the question itself is valid. A better example is when you have, say, an underlying resource, and one function wrapping it in one access object and the second in another. It depends on coding style, of course, but I for one am used to seeing something like this (and thus find it more readable):

class A {
    private Object[] underlying;
    List<Object> getItemsAsList() {
        return Arrays.asList(underlying);
    }
    Object[] getItemsAsArray() {
        return underlying;
    }
}

Iterable getThings() does not seem correct as you are not actually getting anything. Iterable provides access to iterate over a set of items but does not give you those items.

A collection will give you those items, so Collection getThings() seems right.

For example you can be given an iterator for an infinitely long set but no such equivalent collection could be given. This would work because the iterator would return an element at time but a collection would need to collect the infinite amount of objects and return them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM