【问题标题】:When should I use a separate class to represent an empty container?什么时候应该使用单独的类来表示空容器?
【发布时间】:2013-01-07 14:26:58
【问题描述】:

我最近正在阅读“Scala by Example”一书,其中作者创建了一个抽象类来表示一组具有两个子类(EmptySet 和 NonEmptySet)的整数“IntSet”,如下所示:

abstract class Stack[A] { 
  def push(x: A): Stack[A] = new NonEmptyStack[A](x, this)
  def isEmpty: Boolean
  def top: A
  def pop: Stack[A]
}

class EmptyStack[A] extends Stack[A] {
  def isEmpty = true 
  def top = error("EmptyStack.top")
  def pop = error("EmptyStack.pop")
}

class NonEmptyStack[A](elem: A, rest: Stack[A]) extends Stack[A] {
  def isEmpty = false
  def top = elem
  def pop = rest
}

我的问题是:这种将空容器表示为自己的类而不是创建一个具体类来处理空容器和非空情况的范例有多大用处?

【问题讨论】:

    标签: oop containers


    【解决方案1】:

    每个实现都更简单,更易读,因为在实现中不必进行 is-empty-check。这也会导致更好的代码度量值(如圈复杂度)。

    此外,总体而言,它使实现略快,因为空和非空之间的区别不必在运行时完成。据我所知,Scala 的Set 应用了这种技术并实现了不同类型的集合(根据它们的大小使用)以优化性能。

    显然这仅适用于不可变数据结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 2015-05-24
      • 2023-04-02
      • 2011-04-15
      • 2017-04-10
      • 2012-03-19
      • 2018-05-12
      相关资源
      最近更新 更多