vb.net - 如何在对对象执行验证而不是使用常量“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
。我需要任何可能更具可读性的方式。其他语言做的例子也很受欢迎。谢谢!
解决方案
如果一个行条件看起来很混乱,则将其拆分为多个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
推荐阅读
- java - 打印从 SuperClass 继承的字符串属性显示 Null
- vue.js - 无法读取未定义的属性(读取“减少”) - nuxtjs / vuejs
- javascript - 我想与api链接
- laravel - 如何在不创建副本的情况下增加 laravel 模型的数量
- python - 如何迭代多个向量和矩阵并返回单个值?
- database - 有没有更好的方法可以对 Postgres 中的记录进行任意排序?
- java - 指令并行的奇怪风格
- javascript - 某些文件未捆绑在 ViteJS 中
- sql - 在 SQL 中将行显示为列
- java - 如何使用 JUnit 在 Spring 应用程序中测试安全端点?