Let's say we have a function like this:
public void myStart()
{
for (int i = 0; i<10; i++) myFunction(i);
}
private int myFunction(int a)
{
a = foo(a);
a = bar(a);
return a;
}
private int foo(int a)
{
//do something here
//something gnarly here
//etc
return aValue;
}
private int bar(int a)
{
// do something here
//return aValue;
}
Now for whatever reason, our code isn't working. Perhaps it's throwing an error, perhaps it's returning the wrong value, perhaps it's got stuck in an infinite loop.
The first thing any first year programmer, is print to console/std out, (having learned how to print Hello World before learning to use a debugger).
For example to debug this code they might do the following:
private int myFunction(int a)
{
print("before foo: a=" + a);
a = foo(a);
print("before bar: a=" + a);
a = bar(a);
return a;
}
private int foo(int a)
{
//do something here
print ("foo step1: a=" + a);
//something gnarly here
print ("foo step2: a=" + a + " someOtherValue="+ someOtherValue + " array.length= " + someArray.length());
//etc
return aValue;
}
private int bar(int a)
{
// do something here
//return aValue;
}
Now they run the code, they get a big console print out, which they can go through to trace where things are going wrong.
An alternative of course, is to set breakpoints and step through the code at each point.
One major advantage of printing to console, is that the developer can see the flow of the values in one go, without having to click through steps etc.
But the disadvantage is, your code is then riddled with all these print statements that then need to be removed.
(Is it possible perhaps to tell the debugger to print only certain values out to a log?, the breakpoints can then easily be added or removed without actually modifying the code.)
I do still use console printing as a primary debugging method, I'm wondering how common/effective this is in comparison to something else out there.