第五章:设计问题之调试信息
天下维客,你可以修改的网络知识库
[编辑]
为什么要计划调试
假设:您的库很完美。用户只需要学习 API 和使用代码就可以了。对吗?
错。这种假设决不会(或者很少会)发生。错误不可避免;调试必不可少。
某些情况下,用户会遇到问题,他们需要知道库中到底在发生什么。错误可能是库本身引起的,也可能是用户的代码中的错误,而这个错误只有在库内部才会引发。
[编辑]
一小段文本有很大帮助
如果您的库附带了源代码,那么用户可能会考虑使用调试器,但不应该指望用户会那样做。
解决这个不可避免的问题的更好方法是将调试语句 println() 添加到代码中,以强迫每一段代码都报告它在做什么。查看此信息通常可以帮助用户了解在什么位置出了错。
以下示例演示了这个技术。用户的代码通过调用静态方法 Server.setDebugStream(),能够安装 PrintStream 对象。实现之后,调试信息将被发送到已提供的流。
// set this to a print stream if you want debug info // sent to it; otherwise, leave it null static private PrintStream debugStream;
// call this to send the debugging output somewhere
static public void setDebugStream( PrintStream ps ) {
debugStream = ps;
}
然后可以通过调用 debug() 方法来打印库的调试信息:
// send debug info to the print stream, if there is one
static public void debug( String s ) {
if (debugStream!= null)
debugStream.println( s );
}


