I suggest separate classes for both counters and the result:
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; } }
to be used in this way
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)"); } }
Thus, there is no static, and each parameter / class clearly describes its purpose. I prefer this because it is more expressive, even if this version is the longest (due to the boiler plate of additional classes).
source share