使案例类密封是一种好习惯吗? [英] Is it good practice to make case classes sealed?

查看:44
本文介绍了使案例类密封是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

密封类的主要原因似乎是这允许编译器在对这些类进行模式匹配时进行穷尽性搜索.假设我有用于模式匹配的数据类型.玩具示例:

The main reason to seal classes seems to be that this allows the compiler to do exthaustivity searches when pattern matching on those classes. Say I have data types meant for pattern matching. Toy example:

sealed trait Statement
case class Assign(name: String, value: Int) extends Statement
case class Print(name: String) extends Statement
case class IfZero(name: String, thenn: Statement, els: Option[Statement]) extends Statement
case class Block(statements: List[Statement]) extends Statement

这些类的用例是通过模式匹配来使用它们:

The use case for these classes would be to consume them through pattern matching:

def execute(statement: Statement): Unit = statement match {
    case Assign(name, value)      => ???
    case Print(name)              => ???
    case IfZero(name, thenn, els) => ???
    case Block(statements)        => statements foreach { execute(_) }
  }

为此,Statement trait 是 sealed 以便编译器可以在我忘记 match 语句中的一种语句类型时警告我.但是案例类呢?Case 类不能相互继承,但 trait 和普通类可以.那么,密封案例类也是一种好习惯吗?如果我不这样做会出什么问题?

To this end, the Statement trait is sealed so that the compiler can warn me if I forget one statement kind in the match statement. But what about the case classes? Case classes cannot inherit from each other, but traits and ordinary classes can. So, is it good practice to seal the case classes as well? What could go wrong if I don't?

推荐答案

您不必密封案例类,但您应该将它们标记为 final 并因此禁止任何进一步的继承关系.使它们密封仅在您想对其子类进行详尽检查时才有用,这不是一个很可能的用例.

You don't have to seal the case classes but you should mark them as final and therefore forbid any further inheritance relationship. Making them sealed is only useful when you want exhaustiveness checking on its subclasses, which is not a very likely use case.

默认将所有类标记为 final 是一件好事,因为它禁止您的 API 用户在覆盖其方法时更改这些类的行为.如果您没有专门将类设计为子类化,则子类化可能会导致应用程序中出现错误,因为子类化后的类不再执行其预期的操作.

Marking all classes as final by default is a good thing because it forbids the users of your API to change the behavior of these classes when they override its methods. If you didn't specifically design your class to be subclassed, it may happen that the subclassing leads to bugs in your application because the subclassed class is no longer doing what it was intended to do.

这篇关于使案例类密封是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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