Programming Tip #8 - Don’t use print statements to debug
I was reading through the “Ten Commandments for Java Developers“. One of the commandments was about using print lines. I think using the print statement is the most common mistake that any developer does. I think it has become habit when you want to debug, you add a print statement and see if the execution reaches that point. I am not complaining about the approach but the side effect has impacts. Since the print statements are scattered across it is most likely that a developer forgets to remove them when the code moves on to the next stage. Unless the code reviewer deeply goes into the code and catches it and gets it corrected it is more likely that one or two slip and get into the code where it gets deployed in the server.
Print statements consume resource in terms of I/O operations. It is a good practice that developers start using logging frameworks for debugging process from the beginning. You might ask what difference does it make because even the log framework has to write the statements to a log file which is again an I/O operation. Agreed, but the log framework is built efficiently and tested for performance. And log operations can be configured to be environment specific. Below are the advantages of using a log framework.
- Most of the log frameworks allow you to set a log level mode which identifies when a particular log statement should execute. For example log4j defines 5 log levels, viz., debug, info, warn, error and fatal. If there is a log debug statement and the logging level is at a Warn mode then the debug statements are not executed. In a development environment debugging would be required but in a production environment you might want only errors to be logged, so it is just a change in the log property file.
- The logging framework is loosely coupled with your application. Which means the framework can act independently on a separate thread, you just pass on the message and it takes care of putting it in the log file. And even if something goes wrong in the log framework, it does not stop your application.
- The log framework might allow additional features like log rotation which helps in creating a new log file every day or a specified duration. This way older log files could be cleared off which will free disk space.









