Last active
December 21, 2015 04:48
-
-
Save klumsy/6251788 to your computer and use it in GitHub Desktop.
Example of situations where the compiler is telling you that all code paths need a return value, however by the logic of your code, they all do.. so you end up having to write a return statement (or throw an exception) somewhere that will never go, just for it to compile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Retry | |
{ | |
public static IEnumerable<T1> Expression<T1>( | |
int retries, | |
Func<IEnumerable<T1>> action) | |
{ | |
if (retries < 1) throw new Exception("must have 1 or more retries"); | |
var iterations = 1; | |
while (iterations <= retries) | |
{ | |
try | |
{ | |
Debugger.Log(0, "", "processing iteration " + iterations.ToString() + "\r\n"); | |
return action(); | |
} | |
catch(Exception ex) | |
{ | |
if (iterations >= retries) | |
{ | |
throw ex; | |
} | |
iterations++; | |
} | |
} | |
throw new InvalidOperationException("Unexpected code path reached. Algorithmically this should not happen."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The compiler is right to complain. You aren't ensuring that in every invocation retries will be larger than iterations. If someone calls you with a retries value of -3, your loop will never be entered.
There really isn't an elegant solution. Code contracts could help enforce the situation that you are assuming to always be true (retries >= 1), but beyond that, puking when the impossible happens isn't a bad choice. After all, that would be an "exceptional" condition, no?