luolong
7/23/2011 - 7:59 PM

Blog: When in doubt, Maybe can help

Blog: When in doubt, Maybe can help

public abstract Maybe<T> {
  private Maybe() {/* hide the constructor */}

  /**
   * Instances of Maybe that have a value
   */
  public final class Some<T> extends Maybe<T> {
    public final T value;
    private Some(T value) {
      this.value = value;
    }
  }

  /**
   * Instances of Maybe that represent no value (eg. equivalents to null)
   */
  public final class None<T> extends Maybe<T> {
    private None() { }
  }
}
public Maybe<Entity> doSomething(final String name) {
  return Maybe
       .some(CacheingService.get("cachedResourceName"))
       .when((Resource res) -> res.hasSomePropertyOrOther())
       .or(() => {
           Resource res = ResourceFactory.create();
           CacheingService.put("cachedResourceName", res);
           return res;
       })
       .apply((Resource res) -> res.load(name));
}
public Maybe<Entity> doSomething(final String name) {
  return Maybe.some(CacheingService.get("cachedResourceName"))
       .when(new Predicate<Resource>() {
         public boolean apply(Resource res){
           // here I know, res is never null
           return res.hasSomePropertyOrOther();
         }
       })
       .or(new Supplier<Resource>(){
         public Resource get() {
           // the creation of a resource will be delayed until it is actually needed
           Resource res = ResourceFactory.create();
           CacheingService.put("cachedResourceName", res);
           return res;
         }
       })
       .apply(new Function<Resource, Entity>(){
         public Entity apply(Resource res){
           return res.load(name);
         }
       });
}