I have a SearchService
which uses an algorithm for querying a database and returing the results. There are a couple of different formats the data can be returned as, depending on what the invoker wants from the service. These formats are:
Currently my SearchService looks like:
public interface SearchService {
public List<People> searchPeopleReturnEntity(SearchRequest request);
public List<Long> searchPeopleReturnId(SearchRequest request);
public List<SearchResult> searchPeopleReturnSearchResult(SearchRequest request);
}
I'm looking for advice on best practices regarding this. Currently the naming convention seems pretty clunky and I believe there is a better solution than what I have now.
I'd call them something simple like getPeople
, getIds
, getSearchResults
.
If you need these same 3 methods for entities other than people, I'd consider making some generic intermediate type defining them, allowing you to write something like this:
List<People> people = service.getPeople(request).asEntities();
List<Long> fooIds = service.getFoos(request).asIds();
// or something like this
List<People> people = service.searchPeople().getEntities(request);
我将它们findPeople()
, findPeopleIDs()
和findPeopleResults()
。
If your service can return other instances as well (besides People), I'd name them
If SearchResult
is used for people only, I'd also name it PeopleSearchResult
. Otherwise I'd give it a generic parameter like SearchResult<T>
and then List<SearchResult<People>> getPeopleSearchResult()
.
or you can use the searchBy...
approach? though I agree that denotes you will return same results. Perhaps you can refactor a bit:
so your searc... methods always return ID's and then you have specialized functions to transform those into "proper" search results?
如果不明显,这种方法没有真正的“最佳实践”命名方案。
One idea might be:
public <T> T findPeople(SearchRequest request, Class<T> resultClass);
You can then return different things according to whether resultClass is Person.class, Long.class, or SearchResult.class.
Or, less horribly, you could do:
public <T> T findPeople(SearchRequest request, ResultConverter<T> resultConverter);
Where ResultConverter is an interface which takes some sort of raw search result and returns a suitable converted result. You could have canned instances for the common ones:
public class ResultConverters {
public static final ResultConverter<Long> ID;
public static final ResultConverter<Person> PERSON;
public static final ResultConverter<SearchResult> SEARCH_RESULT;
}
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.