Reputation: 67958
In PHP, I always just var_dump
'd everything. In Java, when I'm debugging a program such as implement BFS. I am finding it extremely difficult to just System.out.println
everything, especially when there are tons of loops.
I think I have a poor practice and workflow. I could use JUnit, but when I have to go through every step to make sure every little thing is true or false and if variables are setting properly and checking each and every section, I am not sure if JUnit is any faster than System.out.println
.
I am sure I might be doing something wrong, so I wanted to ask the community for better practices.
Edit: I use Eclipse, just to let you guys know. However, I don't know how to utilize every aspect of it. I just write code, debug, and compile. Sometimes JUnit, when I am required to use it.
Upvotes: 2
Views: 227
Reputation: 63
I'm still quite new to Java coding, but I've found it very helpfully to create an Debug
class and calling it instead of doing a lot of System.out.println
calls.
My debuging class look something like this..
public class Debug {
private static boolean debugActive = true;
public static void setDebug(boolean debug) {
Debug.debugActive = debug;
}
public static void print(String str) {
if (debugActive) {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];
String methodName = e.getMethodName();
System.out.print("[" + e + "]");
System.out.print(" => " + str);
System.out.println(" <= ");
}
}
public static void print(int x) {
print(x + "");
}
}
So calling it from the program
[...]
Debug.print(DB_User);
Debug.print(DB_Pass);
Debug.print(database);
Debug.print(host);
Debug.print(port);
[...]
Debug.setDebug(true);
DbIniParser ini = new DbIniParser();
ini.readFile();
Debug.setDebug(false);
This provides a output as..
[hospitalcase.DbIniParser.readFile(DbIniParser.java:35)] => hjess <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:36)] => password <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:37)] => myFunnyDatabase <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:38)] => localhost <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:39)] => 3306 <=
By using a class itself the output could be changed to be a log file or something else.
Please mind I've only done programming in 3 months so this way might not be optimal, but I've found it quite useful instead for doing System.out.print
every time.
Upvotes: 1
Reputation: 38152
I strongly recommend to use an IDE such as NetBeans or Eclipse. They come with a debugger.
Upvotes: 0
Reputation: 23373
Instead of just printing debug information to the console, use a logging system like log4j.
This offers dynamic loglevels and logging can be send to a set of rotating files through configuration. (I.e. log lots of data while developing, and only log the errors in production without having to change the course code.)
Upvotes: 2