Skip to content

Instantly share code, notes, and snippets.

@martinsson
Created April 16, 2011 15:49
Show Gist options
  • Save martinsson/923217 to your computer and use it in GitHub Desktop.
Save martinsson/923217 to your computer and use it in GitHub Desktop.
A solution to the duplication puzzle at the Grenoble Dojo
package code.puzzles;
import code.puzzles.TheRestOfTheCode.Products;
import code.puzzles.TheRestOfTheCode.Rebates;
import code.puzzles.TheRestOfTheCode.Webservice;
import code.puzzles.TheRestOfTheCode.WebserviceException;
public class WebserviceHelper {
private Webservice webservice;
public Products getProductsByCategoryAndQuantity(final Integer category, final Integer quantity) throws WebserviceException{
return getProductsForCategoryAndQuantity(category, quantity)
.invokeSafely();
}
public Rebates getRebates(final Products products) throws WebserviceException{
return getRebatesFor(products)
.invokeSafely();
}
public WsInvoker<Products> getProductsForCategoryAndQuantity(final Integer category, final Integer quantity) {
return new WsInvoker<Products>() {
public Products invoke() {
return webservice.getProducts(category, quantity);
}
public String errorMessage() {
return "failed invoking the webservice with arguments " + category + " and " + quantity;
}
};
}
public WsInvoker<Rebates> getRebatesFor(final Products products) {
return new WsInvoker<Rebates>() {
public Rebates invoke() {
return webservice.getRebates(products);
}
public String errorMessage() {
return "failed to get rebates for " + products;
}
};
}
}
=======
package code.puzzles;
import code.puzzles.TheRestOfTheCode.WebserviceException;
public abstract class WsInvoker<T> {
public abstract T invoke();
public abstract String errorMessage();
public T invokeSafely() throws WebserviceException {
T t;
try {
t = invoke();
} catch(RuntimeException e) {
throw new WebserviceException(errorMessage(), e);
}
ifNullThrowError(t);
return t;
}
private void ifNullThrowError(Object object) throws WebserviceException {
if (object==null)
throw new WebserviceException("The webservice returned null");
}
}
===========
package code.puzzles;
public class TheRestOfTheCode {
static class Webservice {
public Products getProducts(Integer category, Integer quantity) {
return new Products();
}
public Products getProducts(String brand) {
return new Products();
}
public Rebates getRebates(Products products) {
return new Rebates();
}
}
static class Products {
}
static class Rebates {
}
@SuppressWarnings("serial")
public static class WebserviceException extends Exception {
public WebserviceException(String string, RuntimeException e) {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment