我的验证员是否可以访问我的整个模型?

时间:2010-05-28 17:32:09

标签: asp-classic single-responsibility-principle

正如标题所述,我想知道我的验证类是否可以访问我的模型中的所有属性。理想情况下,我想这样做是因为某些字段需要10个以上的其他字段来验证它是否有效。我可能但宁愿没有10+参数的功能。或者这会使模型和验证器彼此耦合?这是我的意思的一个小例子。但是这段代码不起作用,因为它给出了无限循环!

Class User
    Private m_UserID
    Private m_Validator

    Public Sub Class_Initialize()
    End Sub

    Public Property Let Validator(value)
        Set m_Validator = value

        m_Validator.Initialize(Me)
    End Property

    Public Property Get Validator()
        Validator = m_Validator
    End Property

    Public Property Let UserID(value)
        m_UserID = value
    End property

    Public Property Get UserID()
        UserID = m_Validator.IsUserIDValid()
    End property End Class

Class Validator
    Private m_User

    Public Sub Class_Initialize()
    End Sub

    Public Sub Initialize(value)
        Set m_User = value
    End Sub

    Public Function IsUserIDValid()
        IsUserIDValid = m_User.UserID > 13
    End Function End Class

Dim mike : Set mike = New User 

mike.UserID = 123456  mike.Validator = New Validator

Response.Write mike.UserID

如果我是对的并且这是一个好主意,我怎样才能用getID属性UserID来修复无限循环?

谢谢。

解决方案

<!-- #include file = "../lib/Collection.asp" -->

<style type="text/css">

td { padding: 4px; }

td.error 
{
    background: #F00F00;
}

td.warning 
{
    background: #FC0;
}

</style>

<%

Class UserModel
    Private m_Name
    Private m_Age
    Private m_Height

    Public Property Let Name(value)
        m_Name = value
    End Property

    Public Property Get Name()
        Name = m_Name
    End Property

    Public Property Let Age(value)
        m_Age = value
    End Property

    Public Property Get Age()
        Age = m_Age
    End Property

    Public Property Let Height(value)
        m_Height = value
    End Property

    Public Property Get Height()
        Height = m_Height
    End Property
End Class

Class NameValidation
    Private m_Name

    Public Function Init(name)
        m_Name = name
    End Function

    Public Function Validate()
        Dim validationObject

        If Len(m_Name) < 5 Then
            Set validationObject = New ValidationError
        Else
            Set validationObject = New ValidationSuccess
        End If

        validationObject.CellValue = m_Name

        Set Validate = validationObject
    End Function
End Class

Class AgeValidation
    Private m_Age

    Public Function Init(age)
        m_Age = age
    End Function

    Public Function Validate()
        Dim validationObject

        If m_Age < 18 Then
            Set validationObject = New ValidationError
        ElseIf m_Age = 18 Then
            Set validationObject = New ValidationWarning
        Else
            Set validationObject = New ValidationSuccess
        End If

        validationObject.CellValue = m_Age

        Set Validate = validationObject
    End Function
End Class

Class HeightValidation
    Private m_Height

    Public Function Init(height)
        m_Height = height
    End Function

    Public Function Validate()
        Dim validationObject

        If m_Height > 400 Then
            Set validationObject = New ValidationError
        ElseIf m_Height = 324 Then
            Set validationObject = New ValidationWarning
        Else
            Set validationObject = New ValidationSuccess
        End If

        validationObject.CellValue = m_Height

        Set Validate = validationObject
    End Function
End Class

Class ValidationError
    Private m_CSSClass
    Private m_CellValue

    Public Property Get CSSClass()
        CSSClass = "error"
    End Property

    Public Property Let CellValue(value)
        m_CellValue = value
    End Property

    Public Property Get CellValue()
        CellValue = m_CellValue
    End Property
End Class

Class ValidationWarning
    Private m_CSSClass
    Private m_CellValue

    Public Property Get CSSClass()
        CSSClass = "warning"
    End Property

    Public Property Let CellValue(value)
        m_CellValue = value
    End Property

    Public Property Get CellValue()
        CellValue = m_CellValue
    End Property
End Class

Class ValidationSuccess
    Private m_CSSClass
    Private m_CellValue

    Public Property Get CSSClass()
        CSSClass = ""
    End Property

    Public Property Let CellValue(value)
        m_CellValue = value
    End Property

    Public Property Get CellValue()
        CellValue = m_CellValue
    End Property
End Class

Class ModelValidator
    Public Function ValidateModel(model)
        Dim modelValidation : Set modelValidation = New CollectionClass

        ' Validate name
        Dim name : Set name = New NameValidation
        name.Init model.Name
        modelValidation.Add name

        ' Validate age
        Dim age : Set age = New AgeValidation
        age.Init model.Age
        modelValidation.Add age

        ' Validate height
        Dim height : Set height = New HeightValidation
        height.Init model.Height
        modelValidation.Add height

        Dim validatedProperties : Set validatedProperties = New CollectionClass
        Dim modelVal
        For Each modelVal In modelValidation.Items()
            validatedProperties.Add modelVal.Validate()
        Next

        Set ValidateModel = validatedProperties
    End Function
End Class

Dim modelCollection : Set modelCollection = New CollectionClass

Dim user1 : Set user1 = New UserModel
user1.Name = "Mike"
user1.Age = 12
user1.Height = 32
modelCollection.Add user1

Dim user2 : Set user2 = New UserModel
user2.Name = "Phil"
user2.Age = 18
user2.Height = 432
modelCollection.Add user2

Dim user3 : Set user3 = New UserModel
user3.Name = "Michele"
user3.Age = 32
user3.Height = 324
modelCollection.Add user3

' Validate all models in the collection
Dim modelValue
Dim validatedModels : Set validatedModels = New CollectionClass
For Each modelValue In modelCollection.Items()
    Dim objModelValidator : Set objModelValidator = New ModelValidator
    validatedModels.Add objModelValidator.ValidateModel(modelValue)
Next

%>

<table>
    <tr>
        <td>Name</td>
        <td>Age</td>
        <td>Height</td>
    </tr>
    <%

    Dim r, c
    For Each r In validatedModels.Items()
        %><tr><%
        For Each c In r.Items()
            %><td class="<%= c.CSSClass %>"><%= c.CellValue %></td><%        
        Next
        %></tr><%
    Next

    %>
</table>

产生Solution image http://i46.tinypic.com/zsvk9z.png

虽然不完美,但它比我开始的方式更好。基本上,我决定使用装饰模式。我的下一步是很可能从每个验证中删除Init()函数,并用SetModel()函数替换它。这样每个验证都可以访问我模型中的每个属性。

谢谢大家。

2 个答案:

答案 0 :(得分:2)

我通常定义一个验证整个模型的验证器;在这种情况下,我会有一个UserValidator类,它有一个接受User的方法并返回一个ValidationResult,其中包含一个验证错误列表。

这允许您在不影响验证的情况下更改User类的实现(例如,您不必在每次添加新属性时向Validator类添加新方法,或者如果您想要更改方法签名更改UserID的验证方式等。)

答案 1 :(得分:1)

我认为您正确使验证器验证整个模型。要打破无限循环,可以将值传递给验证器

Public Property Get UserID()
     UserID = m_Validator.IsUserIDValid(m_userID)
End property 

// in Validator
Public Function IsUserIDValid(userID)
    IsUserIDValid = userID > 13
End Function

或者,如果您更喜欢封装,则可以添加Friend函数来访问属性而无需验证。

Public Property Get UserID()
     UserID = m_Validator.IsUserIDValid()
End property 

Friend Function GetUserID()
   GetUserID = m_userID
End Function

// in Validator
Public Function IsUserIDValid()
    // "private" access - to get the unvalidated property
    IsUserIDValid = m_user.GetUserID > 13
End Function

执行此操作的第三种方法是将对象与验证分开。基类定义所有属性而无需验证。然后定义一个添加验证的子类:

class User
    Private m_userID
    Public Property Get UserID()
         UserID = m_userID
    End property 
End Class

class ValidatedUser inherits User
   Public Overrides Property Get UserID()
       if (m_userID<15)
           // handle invalid case, e.g. throw exception with property that is invalid
       UserID = m_userID
   End Property

   Public Function Validate()
    ' class-level validation
   End Function
End Class

最终版本使用委派来保持基本用户属性与经过验证的属性分开。我们将User设为抽象类,因为我们必须实现 - 一个带有验证,一个带有验证。

Class MustInherit User
   Public MustInherit Property Get UserID()
End Class

' A simple implementation of User that provides the properties
Class DefaultUser Inherits User
   Private m_UserID
   Public Overrides Property Get UserID()
      UserID = m_UserID
   End Property   
End Class

Class ValidatedUser Inherits User
   private Validator m_validator
   private User m_User

   Public Property Let Validator(value)
        Set m_Validator = value
        m_Validator.Initialize(m_User)
        ' note that validator uses m_User - this breaks the infinite recursion
    End Property

   Public Overrides Property Let UserID(value)
      m_User.UserID = value;
   End Property

   Public Overrides Property Get UserID()
      UserID = m_validator.IsUserValid();
   End Property
End Class   

在最后一个示例中,ValidatedUser看起来与原始代码类似,但关键区别在于ValidatedUser本身没有任何属性值 - 它将所有属性访问器委托给m_User对象。 Validator使用m_user对象,该对象提供简单属性而无需验证,因此无限递归消失。

目前,在检索属性时进行验证。我想这样做是因为您希望在数据使用之前对其进行验证,并在分配属性时避免出现瞬态验证错误。除了属性级验证之外,您可能还需要定义一个“整个对象”验证方法,该方法检查对象上的所有属性,尤其是涉及多属性约束的属性。例如,如果您有约束A + B + C&lt; 50,然后检查AB和C作为单独的属性将导致该条件(A + B + C <50)被评估3次,这是不必要的,并且也令人困惑,因为错误将出现在一个特定属性上,当它真的是所有3个属性的问题。您的对象级验证器只能检查一次此条件,并标记一个错误,指示所有3个属性都无效。

以上所有内容都将验证绑定到User类,以便客户端可以使用User而无需担心验证。这种方法有利有弊。好处是透明度 - 客户端可以使用用户对象并在幕后进行验证,而无需明确要求。缺点是它将验证与您的模型紧密联系在一起。另一种方法是将验证与User对象完全分开。这不仅解耦验证,还提供“整体对象”验证。 E.g。

' User is now a simple class (like DefaultUser above '
' with just properties, no validation '
Class UserValidator

   Public Function Validate(user)
     ' validate the given user object, return a list of
     ' validation errors, each validation error object
     ' that describes the property or properties
     ' that caused the validation error and why it's an error     
     ' E.g. '
     Dim ve As ValidationError 
     ve = new ValidationError
     ve.obj = user;   ' the object that failed validation
     ve.property = "userID"
     ve.msg = "userId must be < 15"
     ' potentially put several of these in a list and return to caller     
   End
End Class

操作User的任何代码都必须在进行更改后显式调用Validate,但这通常不是问题,控制级别比自动完成更好。 (根据我的经验,你几乎总是必须在某些时候撤销“自动”动作,因为它们会妨碍它。)

我写的比我想的要多。我希望这有用!

PS:我没有做太多的VB,所以请稍微宽容一下偶然的语法错误。我是OO程序员,所以我知道原则是正确的。我刚刚注意到了“asp-classic”标签 - 一些示例使用了经典asp中可能没有的功能,尽管单独的Validator代码 - 最后一个示例,在经典asp上应该没问题。