Jumping with Option

Billion-Dollar Mistake

Tony Hoare, null的发明者在2009年公开道歉,并将此错误称为Billion-Dollar Mistakejava

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.程序员

Idioms and Patterns

Preconditions

绝大多数public的函数对于传递给它们的参数都须要进行限制。例如,索引值不能为负数,对象引用不能为空等等。良好的设计应该保证“发生错误应尽快检测出来”。为此,经常会在函数入口处进行参数的合法性校验。编程

为了消除大量参数前置校验的重复代码,能够提取公共的工具类库,例如:设计模式

public final class Precoditions {
  private Precoditions() {
  }

  public static void checkArgument(boolean exp, String msg = "") {
    if (!exp) {
      throw new IllegalArgumentException(msg);
    }
  }
  
  public static <T> T requireNonNull(T obj, String msg = "") {
    if (obj == null)
      throw new NullPointerException(msg);
    return obj;
  }

  public static boolean isNull(Object obj) {
    return obj == null;
  }

  public static boolean nonNull(Object obj) {
    return obj != null;
  }
}

使用requireNonNull等工具函数时,经常import static,使其更具表达力。数组

import static Precoditions.*;

系统中大量存在前置校验的代码,例如:安全

public BigInteger mod(BigInteger m) {
  if (m.signum() <= 0)
    throw new IllegalArgumentException("must be positive: " + m);
  ...
}

能够被重构得更加整洁、紧凑,且富有表现力。数据结构

public BigInteger mod(BigInteger m) {
  checkArgument(m.signum() > 0 , "must be positive: " + m);
  ...
}
checkArgument(count > 0, "must be positive: %s", count);</pre>

一个常见的误区就是:对全部参数都进行限制、约束和检查。我将其称为“缺少自信”的表现,由于在一些场景下,这样的限制和检查纯属多余。dom

C++为例,若是public接口传递了指针,对该指针作前置校验无可厚非,但仅仅在此作一次校验,其在内部调用链上的全部private子函数,若是要传递此指针,应该将其变动为pass by reference;特殊地,若是是只读,为了作到编译时的安全,pass by const-reference更是明智之举。ide

能够获得一个推论,对于private的函数,你对其调用具备彻底的控制,天然保证了其传递参数的有效性;若是非得对其private的参数进行前置校验,应该使用assert。例如:函数

private static void <T> sort(T a[], int offset, int length) {
  assert a != null;
  assert offset >= 0 && offset <= a.length;
  assert length >= 0 && length <= a.length - offset;
  
  ...
}

Avoid Pass/Return Null

private final List<Product> stock = new ArrayList<>();

public Product[] filter(Predicate<Product> pred) {
  if (stock.isEmpty()) return null;
  ...
}

客户端不得不为此校验返回值,不然将在运行时抛出NullPointerException异常。

Product[] fakes = repo.filter(Product::isFake);
if (fakes != null && Arrays.asList(fakes).contains(Product.STILTON)) {
  ...
}

通过社区的实践总结出,返回null的数组或列表是不明智的,而应该返回零长度的数组或列表。

private final List<Product> stock = new ArrayList<>();

private static final Product[] EMPTY = new Product[0]; 

public Product[] filter(Predicate<Product> pred) {
  if (stock.isEmpty()) return EMPTY;
  ...
}

对于返回值是List的,则应该使用Collections.emptyXXX的静态工厂方法,返回零长度的列表。

private final List<Product> stock = new ArrayList<>();

public Product[] filter(Predicate<Product> pred) {
  if (stock.isEmpty()) return Collections.emptyList();
  ...
}

Null Object

private final List<Product> stock = new ArrayList<>();

public Product[] filter(Predicate<Product> pred) {
  if (stock.isEmpty()) return Collections.emptyList();
  ...
}

Collections.emptyList()工厂方法返回的就是一个Null Object,它的实现大体是这样的。

public final class Collections {
  private Collections() {
  }
 
  private static class EmptyList<E> 
    extends AbstractList<E> 
    implements RandomAccess, Serializable {
  
    private static final long serialVersionUID = 8842843931221139166L;
  
    public Iterator<E> iterator() {
      return emptyIterator();
    }

    public ListIterator<E> listIterator() {
      return emptyListIterator();
    }
  
    public int size() {return 0;}
    public boolean isEmpty() {return true;}
  
    public boolean contains(Object obj) {return false;}
    public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
  
    public Object[] toArray() { return new Object[0]; }
  
    public <T> T[] toArray(T[] a) {
      if (a.length > 0)
        a[0] = null;
      return a;
    }
  
    public E get(int index) {
      throw new IndexOutOfBoundsException("Index: "+index);
    }
  
    public boolean equals(Object o) {
      return (o instanceof List) && ((List<?>)o).isEmpty();
    }
  
    public int hashCode() { return 1; }
    
    private Object readResolve() {
      return EMPTY_LIST;
    }
  }
    
  @SuppressWarnings("rawtypes")
  public static final List EMPTY_LIST = new EmptyList<>();

  @SuppressWarnings("unchecked")
  public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
  }
}

Null Object表明了一种例外,而且这样的例外具备特殊性,它是一个有效的对象,对于用户来讲是透明的,是感受不出来的。使用Null Object,遵循了"按照接口编程"的良好设计原则,而且让用户处理空和非空的状况获得了统一,使得因缺失null检查的错误拒之门外。

Monadic Option

Null Object虽然很优雅地使得空与非空获得和谐,但也存在一些难以忍受的状况。

  • 接口发生变化(例如新增长一个方法),表明Null Object的类也须要跟着变化;

  • Null Object在不一样的场景下重复这一实现方式,其本质是一种模式的重复;

  • 有时候,引入Null Object使得设计变得更加复杂,每每得不偿失;

Option的引入

问题的本质在哪里?null表明的是一种空,与其对立的一面即是非空。若是将其放置在一个容器中,问题便获得了很完美的解决。也就是说,若是为空,则该容器为空容器;若是不为空,则该值包含在容器之中。

Scala语言表示,能够创建一个Option的容器。若是存在,则用Some表示;不然用None表示。

sealed abstract class Option[+A] {
  def isEmpty: Boolean
  def get: A
}

case class Some[+A](x: A) extends Option[A] {
  def isEmpty = false
  def get = x
}

case object None extends Option[Nothing] {
  def isEmpty = true
  def get = throw new NoSuchElementException("None.get")
}

这样的表示有以下几个方面的好处:

  • 对于存在与不存在的值在类型系统中得以表示;

  • 显式地表达了不存在的语义;

  • 编译时保证错误的发生;

问题并无那么简单,若是以下使用,并无发挥出Option的威力。

def double(num: Option[Int]) = {
  num match {
    Some(n) => Some(n*2)
    None => None
  }
}

Option视为容器,让其处理Some/None获得统一性和一致性。

def double(num: Option[Int]) = num.map(_*2)

也可使用for Comprehension,在某些场景下将更加简洁、漂亮。

def double(num: Option[Int]) = for (n <- num) yield(n*2)

Option的本质

经过上例的能够看出来,Option本质上是一个Monad,它是一种函数式的设计模式。用Java8简单地形式化一下,能够以下形式化地描述一个Monad

interface M<A> {
  M<B> flatMap(Function<A, M<B>> f);
  
  default M<B> map(Function<A, B> f) {
    return flatMap(a -> unit(f(a)));
  }
  
  static M<A> unit(A a) {
    ...
  }
}

同时知足如下三条规则:

  • 右单位元(identity),既对于任意的Monad m,则m.flatMap(unit) <=> m

  • 左单位元(unit),既对于任意的Monad m,则unit(v).flatMap(f) <=> f(v)

  • 结合律,既对于任意的Monad m, 则m.flatMap(g).flatMap(h) <=> m.flatMap(x => g(x).flatMap(h))

在这里,咱们将Monad的数学语义简化,为了更深入的了解Monad的本质,必须深刻理解Cathegory Theory,这比如你要吃披萨的烹饪精髓,得学习意大利的文化。但这对于大部分的程序员要求优势太高,但不排除部分程序员追求极致。

Option的实现

Option的设计与List类似,有以下几个方面须要注意:

  • Option是一个Immutablity Container,或者是一个函数式的数据结构;

  • sealed保证其类型系统的封闭性;

  • Option[+A]类型参数是协变的,使得None能够成为任意Option[+A]的子对象;

  • 能够被for Comprehension调用;

sealed abstract class Option[+A] { self =>
  def isEmpty: Boolean
  def get: A
  
  final def isDefined: Boolean = !isEmpty

  final def getOrElse[B >: A](default: => B): B =
    if (isEmpty) default else this.get

  final def map[B](f: A => B): Option[B] =
    if (isEmpty) None else Some(f(this.get))

  final def flatMap[B](f: A => Option[B]): Option[B] =
    if (isEmpty) None else f(this.get)

  final def filter(p: A => Boolean): Option[A] =
    if (isEmpty || p(this.get)) this else None

  final def filterNot(p: A => Boolean): Option[A] =
    if (isEmpty || !p(this.get)) this else None

  final def withFilter(p: A => Boolean): WithFilter = new WithFilter(p)

  class WithFilter(p: A => Boolean) {
    def map[B](f: A => B): Option[B] = self filter p map f
    def flatMap[B](f: A => Option[B]): Option[B] = self filter p flatMap f
    def foreach[U](f: A => U): Unit = self filter p foreach f
    def withFilter(q: A => Boolean): WithFilter = new WithFilter(x => p(x) && q(x))
  }

  final def foreach[U](f: A => U) {
    if (!isEmpty) f(this.get)
  }

  final def collect[B](pf: PartialFunction[A, B]): Option[B] =
    if (!isEmpty) pf.lift(this.get) else None

  final def orElse[B >: A](alternative: => Option[B]): Option[B] =
    if (isEmpty) alternative else this
}

case class Some[+A](x: A) extends Option[A] {
  def isEmpty = false
  def get = x
}

case object None extends Option[Nothing] {
  def isEmpty = true
  def get = throw new NoSuchElementException("None.get")
}

for Comprehension的本质

for Comprehension实际上是对具备foreach, map, flatMap, withFilter访问方法的容器的一个语法糖。

首先,pat <- expr的生成器被解释为:

// pat <- expr
pat <- expr.withFilter { case pat => true; case _ => false }

若是存在一个生成器和yield语句,则解释为:

// for (pat <- expr1) yield expr2
expr1.map{ case pat => expr2 }

若是存在多个生成器,则解释为:

// for (pat1 <- expr1; pat2 <- expr2) yield exprN
expr.flatMap { case pat1 => for (pat2 <- expr2) yield exprN }
expr.flatMap { case pat1 => expr2.map { case pat2 =>  exprN }}

对于for loop,可解释为:

// for (pat1 <- expr1; pat2 <- expr2;...) exprN
expr.foreach { case pat1 => for (pat2 <- expr2; ...) yield exprN }

对于包含guard的生成器,可解释为:

// pat1 <- expr1 if guard
pat1 <- expr1.withFilter((arg1, arg2, ...) => guard)

Others

  • Stream

  • Promise

  • Either

  • Try

  • Validation

  • Transaction

后需文章将逐一解开它们的面纱,敬请期待!

相关文章
相关标签/搜索