在榆木中什么是不透明类型?为什么它很有价值? [英] What is an opaque type in Elm and why is it valuable?

查看:36
本文介绍了在榆木中什么是不透明类型?为什么它很有价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前使用过类型,但不知道什么是不透明类型。我也看到了它的提法。

I've used types before but don't know what an opaque type is. I've seen it mentioned as well. Is it better to expose an opaque type than a type alias?

推荐答案

让我们首先查看类型别名来回答这个问题:

Let’s answer this question by first looking at type aliases:

类型别名是完全透明的。这意味着任何其他导入它的模块都可以完全访问其内部工作方式。假设我们有一个 User 模块公开了 User 类型:

A type alias is fully transparent. This means that any other module importing it will have full access to its inner workings. Let’s say we’ve got a User module exposing a User type:

module User exposing User

type alias User =
    { userName : String
    , age : Int
    }

任何导入 User 的人都可以操纵数据,例如 newUser = {oldUser |年龄= 25} 。或执行 someUser =用户账单 27 。当您可以控制它们存在的上下文时,这些操作就很好。

Anyone importing User can manipulate the data, e.g. newUser = { oldUser | age = 25 }. Or do someUser = User "Bill" 27. These manipulations are fine when you have control over the context that they exist in.

但是,如果 User 是其中的一部分图书馆,那么对 User 类型的每次更改对使用图书馆的人来说都是一个重大更改。例如,如果将 email 字段添加到 User ,则构造函数示例( someUser =用户 Bill 27 )将给出编译器错误。

However, if User is part of a library then every change to the User type is a breaking change to people that use the library. For example, if an email field is added to User, then the constructor example (someUser = User "Bill" 27) will give a compiler error.

即使在项目代码库内部,类型别名也可以提供太多信息其他模块,导致代码难以维护和发展。也许 User 在某个时候发生了巨大变化,并具有一组全新的属性。无论代码在何处操纵 User s,都需要进行更改。

Even inside of a project codebase, a type alias can provide too much information to other modules which leads to code that is difficult to maintain and evolve. Perhaps a User changes drastically at some point and has a completely new set of properties. This would require changes wherever the code manipulates Users.

不透明类型很有价值,因为它们避免了这些问题。这是 User 的不透明版本:

Opaque types are valuable because they avoid these issues. Here’s an opaque version of User:

module User exposing User

type User =
    User
        { userName : String
        , age : Int
        }

使用此版本,其他模块无法直接访问或操作数据。通常,这意味着您将制作并公开一些吸气剂和功能:

With this version, other modules cannot access or manipulate the data directly. Often, this means you will make and expose some getter and functions:

initUser : String -> Int -> User
userName : User -> String
age : User -> String
setAge : Int -> User -> User

这是更多工作,但它具有以下优点:

This is more work, but it has advantages:


  • 其他模块仅关心 User 函数,不需要知道类型中的数据

  • 可以在不破坏包含模块外部代码的情况下更新类型

  • Other modules only care about the User functions and don’t need to know what data is in the type
  • The type can be updated without breaking code outside the containing module

大部分解释来自 @wintvelt elmlang.slack.com

这篇关于在榆木中什么是不透明类型?为什么它很有价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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