Click here to Skip to main content
11,493,233 members (62,537 online)
Click here to Skip to main content

Tagged as

Call Functions Until One Meets Condition

, 1 May 2012 CPOL 28.4K 17
Rate this:
Please Sign up or sign in to vote.
Call a series of functions until the return value meets a condition without a chained-if or short-circuiting.

Thanks to cechode for inspiring this tip/trick. Suppose you have the following functions:

bool Step1()
{
    return true;
}
bool Step2(int val1, int val2)
{
    return val1 == val2;
}
bool Step3()
{
    MessageBox.Show("I will be reached.");
    return false;
}
bool Step4()
{
    throw new Exception("This should be impossible!");
}
Function Step1() As Boolean
    Return True
End Function

Function Step2(ByVal val1 As Integer, ByVal val2 As Integer) As Boolean
    Return val1 = val2
End Function

Function Step3() As Boolean
    MessageBox.Show("I will be reached.")
    Return False
End Function

Function Step4() As Boolean
    Throw New Exception("This should be impossible!")
End Function

If you want to execute each of those in sequence until one returns false, you can do the following:

new Func<bool>[]
{
    Step1,
    // You can use a lambda to wrap a function with a different signature.
    () => Step2(1, 1),
    Step3,
    Step4,
    // You can use a lambda to avoid the use of a function.
    () => 0 == 1
}.Any((step) => !step());
' This is achieved fairly easily in VB.NET
Select Case False
    Case Step1()
    Case Step2(1, 1)
    Case Step3()
    Case Step4()
    Case 0 = 1
End Select

Note that the result need not be true or false; it can be any value or condition. I could, for example, process each function until the result is an integer greater than or equal to 5 (Note that in VB.NET the Select Case statement can't handle conditions, it can only handle values, so the code is modified accordingly):

// This assumes each "Step" function from above returns an int rather than a bool.
new Func<int>[]
{
    Step1,
    () => Step2(1, 1),
    Step3,
    Step4,
    () => 0 + 1
}.Any((step) => step() >= 5);
' VB.NET.
Dim steps() As Func(Of Integer) =
{
    AddressOf Step1,
    Function() Step2(1, 1),
    AddressOf Step3,
    AddressOf Step4,
    Function() 0 + 1
}
 
' We test against a condition rather than a value.
steps.Any(Function([step]) [step]() >= 5)

The condition >= 5 is a very short one, so this won't save you any typing over the short-circuiting technique shown below. However, it would save you some typing for longer conditions. Specifying the condition only once rather than for each value also reduces the probability that you will make a mistake when typing. And if you change the condition later on, you only have to change the condition in one place rather than many. Here is the short-circuiting approach, which leads to duplicated code:

// Don't do this.
if (Step1() >= 5 ||
    Step2(1, 1) >= 5 ||
    Step3() >= 5 ||
    Step4() >= 5 ||
    0 + 1 >= 5)
{ }
' VB.NET. Don't do this.
If Step1() >= 5 OrElse
Step2(1, 1) >= 5 OrElse
Step3() >= 5 OrElse
Step4() >= 5 OrElse
0 + 1 >= 5 Then
End If

While shorter for this example (due to the short condition), this code also has the maintenance problems and higher probability of human error explained above.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

AspDotNetDev
Web Developer
United States United States
  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
GeneralMy vote of 5 Pin
Pravin Patil, Mumbai26-Jun-12 22:02
memberPravin Patil, Mumbai26-Jun-12 22:02 
QuestionVery nice trick Pin
zenwalker19857-Jun-12 6:37
memberzenwalker19857-Jun-12 6:37 
GeneralMy vote of 5 Pin
thatraja1-May-12 19:52
mvpthatraja1-May-12 19:52 
GeneralRe: Definitely makes more sense if you are doing an operation th... Pin
Andrew Rissing30-Mar-11 4:42
memberAndrew Rissing30-Mar-11 4:42 
GeneralRe: Done updating. Pin
AspDotNetDev29-Mar-11 11:05
protectorAspDotNetDev29-Mar-11 11:05 
GeneralRe: Cool, I'll let you know once I'm finished making updates. I ... Pin
AspDotNetDev29-Mar-11 7:26
protectorAspDotNetDev29-Mar-11 7:26 
GeneralRe: I'll keep an eye out for the update, because at this point I... Pin
Andrew Rissing29-Mar-11 6:46
memberAndrew Rissing29-Mar-11 6:46 
GeneralReason for my vote of 5 Makes you think, and then you are go... Pin
FDW24-Jun-11 0:57
memberFDW24-Jun-11 0:57 
Generalhow do i move my alternate from a pending state? ( been like... Pin
cechode29-Mar-11 5:33
membercechode29-Mar-11 5:33 
GeneralRe: It requires approval from another person. Looks like somebod... Pin
AspDotNetDev29-Mar-11 7:25
protectorAspDotNetDev29-Mar-11 7:25 
GeneralI agree with Jose. While interesting academically, what is ... Pin
Andrew Rissing29-Mar-11 5:01
memberAndrew Rissing29-Mar-11 5:01 
GeneralRe: Good question. This version can compare against more than ju... Pin
AspDotNetDev29-Mar-11 5:28
protectorAspDotNetDev29-Mar-11 5:28 
GeneralRe: I agree with Jose. While interesting academically, what is ... Pin
frankazoid1-May-12 13:17
memberfrankazoid1-May-12 13:17 
GeneralI like the aproach...... but, I supose: bool ret= Step1() ... Pin
Jose David Pujo29-Mar-11 0:48
memberJose David Pujo29-Mar-11 0:48 
GeneralRe: FYI, I updated the tip/trick to show how this goes beyond sh... Pin
AspDotNetDev29-Mar-11 12:41
protectorAspDotNetDev29-Mar-11 12:41 
GeneralReason for my vote of 5 Great snippet. Pin
Aamir Butt29-Mar-11 0:18
memberAamir Butt29-Mar-11 0:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 1 May 2012
Article Copyright 2011 by AspDotNetDev
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid