在Swift中使用value objects

博客围绕Swift中验证用户名的代码展开,指出原代码需在各处调用验证函数的缺点。介绍了值对象概念,其创建时自带验证,拿到即已通过验证。还提及参考系统的设计,具有安全、扩展性强的好处,同时提到contains与allSatisfy的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

验证用户名的代码

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
上面代码的缺点:在其他地方使用会重复

``` swift
extension 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的区别

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

参考:Improving your Swift code using value objects

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值