The following scenario happened to me several times.
I programmed a algorithm that solves a certain problem. It works fine and finds the correct solutions. Now, I want to have an option to tell the algorithm "write a full explanation of how you got to the solution". My goal is to be able to use the algorithm in online demonstrations, tutorial classes, etc. I still want to have an option to run the algorithm in real time, without the explanations. What is a good design pattern to use?
EXAMPLE: Suppose I implement this method for finding the greatest common divisor. The current implemented method returns the correct answer, but with no explanations. I want to have an option for the method to explain its actions, like:
Initially, a=6 and b=4. The number of 2-factors, d, is initialized to 0.
a and b are both even, so we divide them by 2 and increment d by 1.
Now, a=3 and b=2.
a is odd but b is even, so we divide b by 2.
Now, a=3 and b=1.
a and b are both odd, so we replace a by (a-b)/2 = 1.
Now, a=1 and b=1.
a=b, so the GCD is a*2^d = 2.
The output should be returned such that it can be easily displayed both in console and in web-based applications.
What is a good pattern to provide explanations when needed, while not hurting the real-time performance of the algorithm when explanations are not needed?