什么时候应该使用单独的类表示一个空容器? [英] When should I use a separate class to represent an empty container?

查看:47
本文介绍了什么时候应该使用单独的类表示一个空容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近浏览过"Scala by Example"一书,作者在其中创建了一个抽象类来表示一组具有两个子类(EmptySet和NonEmptySet)的int"IntSet":

I have recently been going through the book "Scala by Example" in which the author creates an abstract class to represent a set of ints "IntSet" with two subclasses (EmptySet and NonEmptySet) as follows:

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
}

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

My question is this: How useful is this paradigm of representing an empty container as its own class instead of creating one concrete class to handle both the empty and non-empty cases?

推荐答案

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

Each implementation is simpler and more readable as the is-empty-check does not have to be done in the implementation. This leads to better code metric values (like cyclomatic complexity) too.

此外,由于不必在运行时进行空和非空之间的区分,因此它通常使实现稍快.据我所知,Scala的 Set 应用了此技术并实现了不同类型的集合(取决于它们的大小)以优化性能.

Moreover, It makes the implementations slightly faster in general, since the distinction between empty and non-empty does not have to be done at runtime. As far as I know, Scala's Set applies this technique and implements different types of sets (used depending on their size) to optimize performance.

显然,这仅适用于不可变的数据结构.

Obviously this works for immutable data structures only.

这篇关于什么时候应该使用单独的类表示一个空容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆