首页 > 解决方案 > 如何在对对象执行验证而不是使用常量“AndAlso”时获得更具可读性的代码?

问题描述

我目前正在从事一个公司项目,我需要检查我们的 API 是否接收到一个包含所有空白变量的对象,然后将错误代码返回给 API 用户。

我们有一个模型,其中包含多个对象(在本例中为文档对象),如果它被遗漏,它只会传递一个具有空白默认值的对象作为其属性(空白字符串,'0' 表示整数,'0001-01 -01' 日期...)。

简而言之,我需要找到一种更易读的方法来检查这些内容,而无需AndAlso像下面的示例那样使用常量,因为对象中有大约 11 个字段:

If guid.isNullOrEmpty AndAlso content.isNullOrEmpty AndAlso fileName Is String.Empty Then 
   Set Validation Message
   Return False
End If

我会这样做: If object.Document.IsNothing,但对象从未完全收到null。我需要任何可能更具可读性的方式。其他语言做的例子也很受欢迎。谢谢!

标签: vb.netvalidation

解决方案


如果一个行条件看起来很混乱,则将其拆分为多个if语句,如果条件失败则返回。

Public Function IsValid() As Boolean
    If guid.isNullOrEmpty Then 
        Return False
    End If

    If content.isNullOrEmpty Then 
        Return False
    End If

    Return True
End Function

替代方法可以是拥有一组谓词

Public Class DocumentValidator
    Private ReadOnly _validations As List(Func(Of Document, Boolean))        

    Public Sub New()
        _validations = New List(Func(Of Document, Boolean)) From
        {
            Function(doc) doc.guid.isNullOrEmpty = False,
            Function(doc) doc.content.isNullOrEmpty = False,
            Function(doc) doc.fileName IsNot String.Empty,
        }
    End Sub

    Public Function Validate(document As Document) As Boolean
        Return _validations.All(Function(validate) validate(document))
    End Function
End Class

// Use Validator
Dim validator = New DocumentValidator()
If validator.Validate(document) Then
    ' Do something
Else
    ' Show error message
End If

推荐阅读