mardi 3 mai 2022

What is the Java pattern to return functions with different signatures based on some condition?

I'm trying to write a Client class which can look up entities from an external data store. The main parameter used to look up entities is a key. The problem is that sometimes a key is just a userId, sometimes it's a combination of userId and productId. So I'd like to enforce the consumer of my Client API to use a key builder specific to an entity. I tried the code below:

import java.util.function.BiFunction;
import java.util.function.Function;

public class Client {
  public Function getBuilder(SomeEnum type) {
    switch (type) {
      case TYPE_X:
        BiFunction<String, String, Entity> builder = (userId, productId) -> {
          String key = userId + "-" + productId;
          // lookup something in external data store based on the key and return the found entity
        };
        return builder;
      case TYPE_Y:
        Function<String, Entity> b = appId -> {
          String key = userId;
          // lookup something in external data store based on the key and return the found entity
        };
        return b;
    }
  }
}

The code doesn't compile of course because the return types don't match. I'm wondering if the code can be fixed and if not what is the correct Java pattern to enforce such builders with different signatures.

Aucun commentaire:

Enregistrer un commentaire