I have the following excerpt from some wonderful legacy code:
Private Sub SomeMethod()
Dim deductibles As List(Of Integer) = GetDeductibles()
deductibles.RemoveAll(AddressOf LessThanMinDed)
EndSub
Private Function LessThanMinDed(ByVal i As Integer) As Boolean
Return i < MinimumDeductible()
End Function
If you're a language snob, we can write it this way:
private void SomeMethod() {
List<int> deductibles = GetDeductibles();
deductibles.RemoveAll(LessThanMinDed);
}
private bool LessThanMinDed(int i) {
return i < MinimumDeductible();
}
MinimumDeductible()
makes a database call. Is there a way to write this without writing something like x = MinimumDeductible() : RemoveAll(Function(i) i < x)
(since lambdas aren't in this version of VB.NET) that will make a call to the database just once?
Work around like so:
Public Class Foo
Private CachedMinimum As Integer
Private Sub SomeMethod()
Dim deductibles As List(Of Integer) = GetDeductibles()
Me.CachedMinimum = MinimumDeductible()
deductibles.RemoveAll(AddressOf LessThanMinDed)
End Sub
Private Function LessThanMinDed(ByVal i As Integer) As Boolean
Return i < CachedMinimum
End Function
End Class
The answer really depends on the language. In C# 2, we didn't have lambda expressions but we did have anonymous methods... so you can write:
List<int> deductibles = GetDeductibles();
deductibles.RemoveAll(delegate(int i) { return i < MinimumDeductible(); });
As far as I'm aware, there's no equivalent in the version of VB that shipped with VS 2005.
See more on this question at Stackoverflow