For a while now I've been playing around with various ways of passing a logical predicate E.G. >= someValue
as an argument to a function. (see: If ComparisonIsTrue(thisPost, ComparisonOperator.NotEqualTo, goodCode) Then Me.Answer and a global enum for comparison operators)
In the end, I've decided to build a CLS_Comparison_Predicate
class with Operator
and RightValue
properties, with a Compare()
function that takes a LeftValue
as an argument.
Thoughts?
Example Usage:
Dim predicate As CLS_Comparison_Predicate
Set predicate = New CLS_Comparison_Predicate
predicate.Operator = GreaterThan
predicate.RightValue = 9000
If predicate.Compare(inputValue) Then
MsgBox "It's over 9,000!"
End If
Enum:
Public Enum ComparisonOperator
NotEqualTo = 0
LessThan = 1
LessThanOrEqualTo = 2
EqualTo = 3
GreaterThanOrEqualTo = 4
GreaterThan = 5
End Enum
Code:
Option Explicit
Private pOperator As ComparisonOperator
Private pRightValue As Variant
Private Const NULL_ERROR_TEXT As String = "Invalid Compare input. Cannot compare against Null"
Private Const OBJECT_ERROR_TEXT As String = "Invalid compare input. Input must be a value, not an object"
Public Property Let Operator(ByVal inputOperator As ComparisonOperator)
pOperator = inputOperator
End Property
Public Property Let RightValue(ByVal inputValue As Variant)
If IsNull(inputValue) Then
PrintErrorMessage NULL_ERROR_TEXT
Stop
ElseIf IsObject(inputValue) Then
PrintErrorMessage OBJECT_ERROR_TEXT
Stop
End If
pRightValue = inputValue
End Property
Public Function Compare(ByVal leftValue As Variant) As Boolean
If IsNull(leftValue) Then
PrintErrorMessage NULL_ERROR_TEXT
Stop
ElseIf IsObject(leftValue) Then
PrintErrorMessage OBJECT_ERROR_TEXT
Stop
End If
Dim isTrue As Boolean
Select Case pOperator
Case NotEqualTo
isTrue = (leftValue <> pRightValue)
Case LessThan
isTrue = (leftValue < pRightValue)
Case LessThanOrEqualTo
isTrue = (leftValue <= pRightValue)
Case EqualTo
isTrue = (leftValue = pRightValue)
Case GreaterThanOrEqualTo
isTrue = (leftValue >= pRightValue)
Case GreaterThan
isTrue = (leftValue > pRightValue)
Case Else
'/ TODO: Error Handling
Stop
End Select
Compare = isTrue
End Function
inputValue
arguments to specify right and left, just looking at the code. \$\endgroup\$Right
andLeft
functions in theVBA.Strings
module? \$\endgroup\$IComparable
interface in there and support object types (those that implement the interface anyway). \$\endgroup\$rightInputValue
\$\endgroup\$