Java fallback pattern -


i'm trying find nice way of implementing service relies on third-party library class. have 'default' implementation use fallback in case library unavailable or can not provide answer.

public interface service {      public object compute1();      public object compute2(); }  public class defaultservice implements service {      @override     public object compute1() {        // ...     }      @override     public object compute2() {         // ...     } } 

the actual implementation of service like:

public class serviceimpl implements service {     service defaultservice = new defaultservice();     thirdpartyservice thirdpartyservice = new thirdpartyservice();      @override     public object compute1() {         try {             object obj = thirdpartyservice.customcompute1();             return obj != null ? obj : defaultservice.compute1();         }          catch (exception e) {             return defaultservice.compute1();         }     }      @override     public object compute2() {         try {             object obj = thirdpartyservice.customcompute2();             return obj != null ? obj : defaultservice.compute2();         }          catch (exception e) {             return defaultservice.compute2();         }     } } 

the current implementation seems duplicate things bit in way actual calls services different, try/catch , default mechanism pretty same. also, if method added in service, implementation alike.

is there design pattern might apply here (proxy, strategy) make code better , make further additions less copy-paste?

you can extract common logic separate method using method references, like:

public class serviceimpl implements service {     service defaultservice = new defaultservice();     thirdpartyservice thirdpartyservice = new thirdpartyservice();      @override     public object compute1() {         return run(thirdpartyservice::customcompute1, defaultservice::compute1);     }      @override     public object compute2() {         return run(thirdpartyservice::customcompute2, defaultservice::compute2);     }      private static <t> t run(supplier<t> action, supplier<t> fallback) {         try {             t result = action.get();             return result != null ? result : fallback.get();         } catch(exception e) {             return fallback.get();         }     } } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -