是否可以强制某条记录尊重某些不变性? [英] Is it possible to enforce that a Record respects some invariants?
本文介绍了是否可以强制某条记录尊重某些不变性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想创建一个表示可接受的最小/最大界限的记录类型:
Suppose I wanted to create a Record type that represents acceptable min/max bounds:
type Bounds = { Min: float; Max: float }
有没有一种方法可以强制执行Min<最大限度?编写validateBounds函数很容易,我只是想知道是否有更好的方法可以做到这一点.
Is there a way to enforce that Min < Max? It is easy to write a validateBounds function, I was just wondering if there was a better way to do this.
我意识到对于这个特定的示例,我可能可以避免暴露两个属性并对参数进行重新排序,所以我们可以尝试
I realized that for this specific example I could probably get away with exposing two properties and re-order the arguments, so let's say we were trying to do
type Person = { Name: string }
姓名"必须至少包含一个字符.
and Name needs to have at least one character.
推荐答案
这是基于保护级别的另一种解决方案:
Here's another solution based on protection levels:
module MyModule =
type Bounds = private { _min: float; _max: float } with
// define accessors, a bit overhead
member public this.Min = this._min
member public this.Max = this._max
static member public Make(min, max) =
if min > max then raise (ArgumentException("bad values"))
{_min=min; _max=max}
// The following line compiles fine,
// e.g. within your module you can do "unsafe" initialization
let myBadBounds = {_min=10.0; _max=5.0}
open MyModule
let b1 = Bounds.Make(10.0, 20.0) // compiles fine
let b1Min = b1.Min
let b2 = Bounds.Make(10.0, 5.0) // throws an exception
// The following line does not compile: the union cases of the type 'Bounds'
// are not accessible from this code location
let b3 = {_min=10.0; _max=20.0}
// The following line takes the "bad" value from the module
let b4 = MyModule.myBadBounds
这篇关于是否可以强制某条记录尊重某些不变性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文