博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在Swift中使用value objects
阅读量:6948 次
发布时间:2019-06-27

本文共 2041 字,大约阅读时间需要 6 分钟。

验证用户名的代码

func authenticate(user: String) {    // make sure usernames are at least three characters    guard user.trimmingCharacters(in: .whitespacesAndNewlines).count >= 3 else {        print("Username \(user) is too short.")        return    }    // make sure usernames contain no invalid characters    let illegalCharacters = ["@", "-", "&", "."]    guard illegalCharacters.contains(where: user.contains) == false else {        print("Username \(user) contains illegal characters.")        return    }    // Proceed with authentication…}``` swift上面代码的缺点:在其他地方使用会重复``` swiftextension String {    func isValidUsername() -> Bool {        guard self.trimmingCharacters(in: .whitespacesAndNewlines).count >= 3 else {            return false        }        let illegalCharacters = ["@", "-", "&", "."]        guard illegalCharacters.contains(where: self.contains) == false else {            return false        }        return true    }}复制代码

上面代码的缺点:需要在每个地方调用isValidUsername()

struct User: Equatable {    let value: String    init?(string: String) {        guard string.trimmingCharacters(in: .whitespacesAndNewlines).count >= 3 else {            return nil        }        let illegalCharacters = ["@", "-", "&", "."]        guard illegalCharacters.contains(where: string.contains) == false else {            return nil        }        self.value = string    }}func authenticate(user: User) {    // Proceed with authentication…}复制代码

值对象:value objects should be both immutable and equatable, but they also add in validation as part of their creation. This means that if you’re handed a value object you know for sure it’s already passed validation – you don’t need to re-validate it, because if it were valid then it couldn’t exist.

设计:参考系统的 URL(string: "This ain't it chief") 好处:安全,扩展性强

注:contains与allSatisfy的区别

// 有一个满足就为truefunc contains(where predicate: (Element) throws -> Bool) rethrows -> Bool// 所以满足就为truefunc allSatisfy(_ predicate: (Element) throws -> Bool) rethrows -> Bool复制代码

参考:

转载于:https://juejin.im/post/5ce7a7556fb9a07eb55f36fd

你可能感兴趣的文章
第四章简介
查看>>
LNMP(linux+nginx+mysql+php)服务器环境配置
查看>>
Linux下redis服务的安装
查看>>
oracle设定菜单全路径
查看>>
使用Qt开发文本编辑器(一):功能介绍
查看>>
一款增加导航选项的控件
查看>>
我的友情链接
查看>>
shape用法知多少
查看>>
oracle power 函数
查看>>
网页头部<meta name="Robots" 用法 <meta>系列用法
查看>>
我的友情链接
查看>>
ubuntu apache操作-工作笔记
查看>>
我的友情链接
查看>>
分布式数据库中间件对比总结(1)
查看>>
暴风影音CEO冯鑫的人生解读
查看>>
动态控制header显示
查看>>
如何使用redhat 6.0 Enterprise企业版虚拟化安装虚拟机
查看>>
idea导出可执行jar包
查看>>
Spring中HttpInvoker远程调用使用实例
查看>>
MariaDB主从搭建与测试
查看>>