Using Validation Rules and Target Object.

Using Validation Rules and Target Object.

Old forum URL: forums.lhotka.net/forums/t/5394.aspx


tarekahf posted on Friday, September 12, 2008

From the book: CHAPTER 8 BUSINESS OBJECT IMPLEMENTATION, starting with page 438, I have questions about the following code for validating the "Role()" Property of the "ProjectResource" Object:

Protected Overrides Sub AddBusinessRules()
ValidationRules.AddRule(AddressOf Assignment.ValidRole, "Role")
End Sub
...
...
Public Function ValidRole(ByVal target As Object, ByVal e As RuleArgs) As Boolean
Dim role As Integer = CType(target, IHoldRoles).Role
If RoleList.GetList.ContainsKey(role) Then
Return True
Else
e.Description = "Role must be in RoleList"
Return False
End If
End Function
...
...
Friend Interface IHoldRoles
Property Role() As Integer
End Interface

As per my understanding, is that the "target" object is the ProjectResource. So, we could have converted the target object using CType to ProjectResource to access the Role() property, and hence to validate it.

What is confusing me here is we have defined IHoldRoles Interface to get the Role() property, and it is not clear to me how this is going to work, and why it is done that way.

Also, why it did not use DirectCast instead of CType ? DirectCasrt is much faster than CType !

Any one can explain to me this point I will appreciate it.

Tarek.

RockfordLhotka replied on Friday, September 12, 2008

The reason for using IHoldRoles is because that code has to work against both ProjectResource and ResourceAssignment types (it is invoked from both), so the interface allows for polymorphism.

Using CType() or DirectCast() is really not as big a deal as people make out - it is a commonly held myth that DirectCast() is radically faster, when in reality it is only faster in a few edge cases.

I (sadly) helped spread that myth early on, but I've since been educated by people who are far more meticulous at testing performance than myself, so I don't worry about it so much anymore.

tarekahf replied on Friday, September 12, 2008

In other words, I can use the "Interface" declaration to put common properties in different classes, in case I need to access then easily in one place for the purpose of normalizing the behavior, correct ?

So, the other alternative, is to use "if typeof object is xyz then" to cast the object type to the appropriate target type to avoid run-time errors, correct ?

Tarek.

RockfordLhotka replied on Friday, September 12, 2008

You can use a number of techniques, including:

 

·         Reflection

·         A common (non-generic) base class

·         A common (non-generic) interface

·         A set of if..type or a switch on type (my least favorite)

 

Rocky

 

Copyright (c) Marimer LLC