is there a way to print each line of source when the program executes without having to insert System.out.println after each line?
Use a debugger. Debuggers provide a number of useful tools to step through your program. Check your IDE, it probably has one.
First a question: Why would you need that? You might use a debugger if it's just for debugging.
If it is for logging purposes, logging each line would be overkill.
Second a suggestion: you might use AOP to log each method call (assignments etc. could not be intercepted), but that might require a lot of work (incorporate AOP into your build process etc.) and might not be worth the hassle.
Eclipse Test & Performance Tools Platform Project has a way to show you a sequence diagram of the program execution:
http://www.eclipse.org/tptp/home/documents/tutorials/profilingtool/profilingexample_32.html
For printing as text, AOP is nice but complicated, debug statements are easiest but most invasive.
I'm pretty sure Eclipse lets you step through the program line by line, the link is unfortunately down for maintenance but maybe check back on it later: http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.user/tasks/task-stepping.htm
Related
When using gdb to debug there are a couple of ways to automate the actions performed when a break point is hit. This is good for cases where I only have compiled code with debug symbols, not source code. It is also nice when I want to instrument something interactively without relying on code reloading to insert print statements.
Is there a way to do this with the Eclipse debugger and Java code? All I need is a way to print objects and variables and then continue from the breakpoint.
You can inject code using conditional breakpoints.
In this example the breakpoint never suspends because of return false;, but always print the absolut path of a file-variable named "file"!
I am working on a java project and I have to extend (add more functionality) it. But I don't know how should I learn the existing one before incorporating them.
Is there any specific path I should follow?
Can I run it in a way so that I can see, statement by statement, the execution of the program?
I am a kind of stuck in understanding it, thanks.
Here is another approach that is hacky, but I've found useful in the past when unable to attach a debugger. If there is a piece of code that you are looking at, but are having a hard time figuring out who is calling it you can throw a new runtime exception, catch it and print the stack trace.
try {
throw new RuntimeException("who is calling me");
} catch (RuntimeException e) {
e.printStackTrace();
}
You can always fire it up in a debugger/your IDE of choice and step through it all you want, though it's probably best to find someone who is more familiar with the source to provide you an overview, or to look for documentation on where to start.
Pick one piece of functionality for which you understand the requirements. Find the entry point for that feature and follow the code for that one feature. It should give you a good understanding of how the architecture works.
Integrating with code that is already written can be very difficult. In my experience, some of the best clues I've gotten about already-written code come from the method signatures (the mapping of the function's input to its output). The method's signature can give you a lot of hints about a program, namely where and especially how that particular method fits in the context of the larger program. Usually, a method signature coupled with a descriptive method name can give you enough information to be dangerous, especially in a typed language like Java.
Although I wouldn't suggest running the code line by line and looking at changes (because this usually amounts to tons of work) but for really ugly but important code sometimes it is necessary (I've definitley done it before using DDD for C programs). In this case, a quick google search reveals http://www.debugtools.com/ , a graphical java debugger, which may do the trick; there also seems to be version of DDD that works with Java.
This is a recurrent question on Stack Overflow. There is already very good answers all around:
https://stackoverflow.com/questions/3147059/taking-over-a-project
Cleaning up a large, legacy Java project
https://stackoverflow.com/questions/690158/how-do-you-learn-other-peoples-code
Also, this book might help: Working Effectively with Legacy Code
"Patience and fortitude conquer all things." - Ralph Waldo Emerson
I would recommend you to start with the debug as well so you can go through the program step by step.
Documentation:
If you have documentation, it’ll be helpful. But it can be a pitfall, as much documentation is out date, they can be misleading you.
Bugfix:
You could start with bugfix or new feature implantation. Start work with small scope, it’ll be easy work. During the bugfix, you could understand the code more and more.
Baseline the code, I generally would use git
Do a build of the application
Run it.
If baseline fails build or process is too complicated, create a branch and fix it
Create a branch and modify a string or something that would show some visible change if you modify the code.
If Javadocs are not created via ant or build files, create a new branch to do this.
If there is no JUnit test cases (or if there are but they don't work), create a branch and fix it.
Create a new branch to do the merge.
The following is if you're using Eclipse or similar product
If you're the only developer, create a new branch and set up project settings for code formatting and cleanup. Then execute the code formatting and cleanup. This would allow you to have a more stable baseline for future work. If not, try to coordinate with others.
Install FindBugs, Checkclipse, PMD to do some simple checks on the code base. Looking at WTFs sometimes will give you a better idea on how things are working (or not)
Install Eclemma and see how much of the code is actually tested.
That is my question. More specifically, I'm trying to get used to Eclipse's debugger and I'd like to know if printing to console is still done in some cases or if it's considered a bad practise that should be entirely avoided. Also, what can be considered as good approach(es) to debugging overall?
Use System.err.println() instead.
Why?
System.out.println() is often redirected to a file or another output, while this is pretty much always printed on the console. It's easier for debugging and also the right way to do it.
Edit (warning: subjective):
Since you asked about whether System.out.println should be entirely avoided: I don't believe in anything that you must always avoid, be it using goto's, crashing your computer with a BSOD, or whatever. Sometimes you just need a quick-and-dirty way to get small things done fast, and it just plain isn't worth the 1 hour you'll spend on it to try to do things the "right" way, instead of a 5-minute fix, no matter how good the "good" way is. Use your judgment when deciding if something should be used or not, but never set rules for yourself like "I'll never use goto!". :)
Edit 2 (example):
Let's say you're debugging a crashing driver and you suspect that an if statement that shouldn't be execute is being executed. Instead of spending three hours finding out how to use ZwRaiseHardError to display a message box, just call KeBugCheck inside the if and crash the darned system. Sure, you'll reboot, but unless your reboot takes hours, you just saved yourself that much time.
The best choice would be a logging library (of course, this adds an extra dependency to your project). Check out commons-logging, for instance.
The main advantage is that you can write your debug messages in the DEBUG level and when you deploy your code, you'll just configure the logger to skip those messages (instead of searching for all occurrences of System.out.println in your code).
One other great advantage is that loggers usually can be configured to write anywhere (even send email messages or SMS) also without touching your code.
Minor point: if your program actually outputs something useful to the console via System.out, you may want to instead print the debugging info to System.err
You should generally strive to have as much debugging as possible (ideally using some standard logger like log4j). This both eases debugging when you're actually developing the program AND allows for much easier debugging of already-released code in production. The benefit is that your code remains unchanged and you don't need to ADD debugf prints, yet by default the logging config can turn off the logging until it's actually needed (or at least turn down the level of logs)
As far as general simple "throw printlns at the wall" debugging, it can sometimes be one of the fastest ways to debug, though it should by no means be the only/main one.
Why can it be useful? Among other reasons, because running a Java program in a debugger may be much slower than outside of it; or because your bug manifests in an environment/situation that can't be easily replicated in your Eclipse debugger.
If the debugging print lines are not going to stay in the code after you've fixed your bug, then do whatever is easiest for you. Lambert's advice of using System.err.println() is a good idea since you can differentiate it from other output that your program may produce. If the debugging print lines are going to stay in your code, then I would advise on using a logging framework like log4j. This way you can dial up or down the level of output based on whether you're trying to debug something or just running in production. Be sure to output things at the right level when using log4j. Don't just log everything at INFO.
I use System.out.println for my debugging in case i have a problem or to inform me that methods have started to make sure everything has worked properly but when I publish the program I always remove it because it slows down the program.
Suppose that I have a Java program within an IDE (Eclipse in this case).
Suppose now that I execute the program and at some point terminate it or it ends naturally.
Is there a convenient way to determine which lines executed at least once and which ones did not (e.g., exception handling or conditions that weren't reached?)
A manual way to collect this information would be to constantly step with the debugging and maintain a set of lines where we have passed at least once. However, is there some tool or profiler that already does that?
Edit: Just for clarification: I need to be able to access this information programmatically and not necessarily from a JUnit test.
eclemma would be a good start: a code coverage tool would allow a coverage session to record the information you are looking for.
(source: eclemma.org)
What you're asking about is called "coverage". There are several tools that measure that, some of which integrate into Eclipse. I've used jcoverage and it works (I believe it has a free trial period, after which you'd have to buy it). I've not used it, but you might also try Coverlipse.
If I understand the question correctly you want more than the standard stacktrace data but you don't want to manually instrument your code with, say, log4j debug statements.
The only thing I can think of is to add some sort of bytecode tracing. Refer to Instrumenting Java bytecode. The article references Cobertura which I haven't used but sounds like what you need...
I've got two versions of a project with a JUnit test. Looking at the diff of the files there's no obvious reason to this, but the test passes on one project but not on the other.
For a while now I've wondered if there was a program that would record a trace through the whole program when it runs and save it to a file. This would be really handy for this exact example where I want a trace through both tests and then I want to diff them together.
Can anyone point me in the direction of a program that might be able to do this, or a way that I could diff the two program's flows?
Cheers
I'd use Aspects for this. Check out AspectJ for instance, it is very easy to design a rule (point cut) that says "For all methods invoked in my Java code, log method name".
If I understand your question correctly looks like this might partially achieve what you are after.
http://www.lambdacs.com/debugger/debugger.html
The Eclipse TPTP project has a trace engine that you might find useful.