Reputation: 15
I'm looking for some way of writing this prettier.
if (n > 1){
function_1();
}
if (n > 2){
function_2();
}
if (n > 3){
function_3();
}
...
if n = 3: function_1 and function2 should run.
I don't think a switch would help here because if n is for example 4 i want it to execute all the functions. Any help is appreciated.
Upvotes: 0
Views: 79
Reputation: 37655
If the order of execution doesn't matter, you could use switch
and take advantage of fall-through.
switch (Math.min(n, 4)) {
case 4: function_3();
case 3: function_2();
case 2: function_1();
}
This executes the methods in the reverse order from your version.
If you need to have the order of execution specified in the question, and you are using Java 8, you could do this.
Deque<Runnable> queue = new ArrayDeque<>();
switch (Math.min(n, 4)) {
case 4: queue.addFirst(MyClass::function_3);
case 3: queue.addFirst(MyClass::function_2);
case 2: queue.addFirst(MyClass::function_1);
}
for (Runnable r : queue)
r.run();
However, I do not recommend either solution. I think your original version is much clearer.
Upvotes: 0
Reputation: 140484
List<Runnable> runnables = Arrays.asList(
() -> function_1(),
() -> function_2(),
() -> function_3()
);
for (Runnable runnable : runnables.subList(0, Math.min(runnables.size(), Math.max(n - 1, 0)))) {
runnable.run();
}
Upvotes: 1