This is where monads and all that jazz show their ugly mugs.
Assuming you are talking about java, you could for example write a runSequentially method that results in letting you write:
runSequentially(() -> sameMethod(), () -> {
// random code
}, number != 250);
Where runSequentially will first run the first Runnable, then the second Runnable - unless the condition is false, in which case it runs the second, then the first.
In java, this is not, however, local mutable variable, checked exception, and control flow transparent which are sufficient downsides that I'm not sure this is a good idea. Especially considering that apparently execution order matters which usually suggests mutating state. But, if you insist, it'd be something like:
public static void runSequentially(Runnable a, Runnable b, boolean flipOrder) {
if (flipOrder) { b.run(); a.run(); }
else { a.run(); b.run(); }
}
Javascript is a lot more laissez-faire (and a totally different language; did you tag it because perhaps you were unaware that 'java' and 'javascript' are completely unrelated? It's a common mistake - in that case, disregard this bit), and doesn't suffer from the transparency issues as much. Javascript has no checked exceptions, javascript lets you mutate outer state (there are some WTFs in javascript-the-language about this, but that's a separate issue). The biggest issue is control flow (you can't as easily break/continue loops in the 'outer' code from within these closures).
Going back to java for a moment, using lambdas (closures) in contexts where:
- The lambda is run 'in-line', that is, you pass the lambda to some method, and once that method returns, the lambda is 'forgotten about' by said method: That method did not store the lambda in a field, did not pass it to another thread, did not pass it to other code that is going to store it in a field or pass it to another thread).
- The code in the lambda is not designed 'functional style' (e.g. it mutates state or does a bunch of I/O), then
you're probably messing up. Lambdas really suck in that environment, those transparency issues are grating then. Note that if the lambda does 'travel' (is stored / moved to another thread), that lack of transparency is in fact a great thing because those 3 'transparencies' become bizarre braintwisters - best to just not allow them.
That's why I recommend against this, if you're writing java. But now you know how one would.