What is the ideal way to define singular and plural in a storage API?

I have an inner storage layer in my application that processes Foo objects. During Get operations, the data layer has significant advantages for clustering, but I actually do multiple calculations in about 10% of cases. Here are a few approaches that I have reviewed:

Approach A:

 interface FooStorage { Foo getFoo(String name); List<Foo> getFoos(List<String> names); } 

Approach B:

 interface FooStorage { List<Foo> getFoos(List<String> names); } class StorageUtility { public static <T> T firstOrNull(List<T> data) { ... } } 

Approach C:

 interface FooStorage { List<Foo> getFoos(String... names); } class StorageUtility { public static <T> T firstOrNull(List<T> data) { ... } } 

The disadvantage of approach A is that there is a larger surface that I have to support.
The drawback of approach B is that the consumer creates a list when 90% of the time I don’t need it. The disadvantage of approach C is the overhead of copying a list to an array in 10% of cases.

Is there a canonical correct way to do this?

+6
source share
1 answer

In this type of situation, I would go for the following construction:

 Foo getFoo(String name) { return firstOrNull(getFoos(name)); } List<Foo> getFoos(String ... names) { return getFoos(Arrays.asList(names)); } List<Foo> getFoos(List<String> names) { .... } 

Your client should use the most appropriate method every time, and if you find that performance requires a more focused approach for getFoo(name) , you can reimplement this single method.

I would say that it is more important that the consumer code is readable (do not create lists to satisfy the API) than storing a few lines of code in the storage interface / implementation.

+1
source

Source: https://habr.com/ru/post/899541/


All Articles