简体   繁体   中英

Java - Avoid pattern duplication

Java In my server code, for each method I will have to do the following

    @Path("...")
    public Response function(...) {
        try {
            result = do some work to get result
            log the result
            return result
        } catch (Exception e) {
            log error
            return error
        }
    }

I will have to duplicate this pattern everywhere and only changing the do some work to get result part for new endpoint.

Is there a way that I can do to reduce this is duplication?

PS do some work to get result can be very something like getting a Json file, or accessing multiple database and calculate the result, and need to be in try-catch block.

You can create a function that looks like this:

  public static <T> T doTheThing(Supplier<T> supp, Supplier<T> errorSupp) {
    try {
      T result = supp.get();
      //log the result
      return result;
    } catch (Exception e) {
      //log error
      return errorSupp.get();
    }
  }

Then you can pass suppliers for a) the actual work and b) the potential error to this function.

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