カウンターと結果の両方に別のクラスをお勧めします。
class Counter {
private int value = 0;
public void inc() {
value++;
}
public int get() {
return value;
}
}
class Result {
public final long value;
public final int calls;
public Result(long value, int calls) {
super();
this.value = value;
this.calls = calls;
}
public final long getValue() {
return this.value;
}
public final int getCalls() {
return this.calls;
}
}
このように使われる
public class FibonacciWithCounter {
static Result fibonacci(long n) {
final Counter counter = new Counter();
final long value = fibonacci(n, counter);
return new Result(value, counter.get());
}
static long fibonacci(long n, Counter counter) {
counter.inc();
if (n == 0)
return n;
else if (n == 1)
return n;
else
return fibonacci(n - 1, counter) + fibonacci(n - 2, counter);
}
public static void main(String[] args) {
final Result result = fibonacci(14);
System.out.println("Result is " + result.value
+ " (" + result.getCalls() + " calls)");
}
}
したがって、静的なものはなく、各パラメーター/クラスはその目的を明確に説明しています。このバージョンが最も長いバージョンであっても (追加のクラスのボイラー プレートのため)、より表現力があるため、私はこれを好みます。