I have a webpage that needs to selectively show or hide a substantial number of controls. Each control's visibility is determined based on which of 3 conditions are true.
So, for example, given the conditions A, B, and C;
- Control1 needs to be visible only when A and B are true and C is false.
- Control2 needs to be visible only when B and C are true and A is false.
- Control3 needs to be visible only when A and C are true and it doesn't care what B is.
- and so on...
If each control looked at every condition, the control logic would be ugly, but doable.
If A Then
If B Then
If C Then
Else
End If
Else
If C Then
Else
End If
End If
Else
If B Then
If C Then
Else
End If
Else
If C Then
Else
End If
End If
End If
But unfortunately, when you mix in the fact that many controls only care about 1 or 2 of the 3 conditions, the code starts to grow into a maintenance nightmare. Here are all 26 of the possible conditions:
A False B Any C Any
A True B Any C Any
A Any B Any C False
A False B Any C False
A True B Any C False
A Any B Any C True
A False B Any C True
A True B Any C True
A Any B False C Any
A False B False C Any
A True B False C Any
A Any B False C False
A False B False C False
A True B False C False
A Any B False C True
A False B False C True
A True B False C True
A Any B True C Any
A False B True C Any
A True B True C Any
A Any B True C False
A False B True C False
A True B True C False
A Any B True C True
A False B True C True
A True B True C True
Is there a better pattern to handle checking for multiple conditions?
Edit: I had started going down the road that Marcelo Cantos suggested, but my A, B, and C conditions are quite long. So I made a helper function:
Dim isMatch = Function(A As Boolean?, B As Boolean?, C As Boolean?) As Boolean
Return (Not A.HasValue OrElse A.Value = SomeLongConditionA) _
AndAlso (Not B.HasValue OrElse B.Value = SomeLongConditionB) _
AndAlso (Not C.HasValue OrElse C.Value = SomeLongConditionC)
End Function
Control1.Visible = isMatch(True, True, False)
Control2.Visible = isMatch(False, True, True)
Control3.Visible = isMatch(True, Nothing, True)