[Edit: Let me rephrase]
Say an object o that occurs in debugging has properties a and b, with values null and Hello. Is it possible to automatically generate the following code for the next debugging session:
if(o.a == null && o.b == "Hello") {
}
When debugging a program that has to cope with complex user inputs, such as a parser for a programming language, I often want to start debugging from a certain point in the process of parsing. I have implemented a simple way of starting when an instruction from a specific line of input code is handled.
However, lines may contain very complex instructions resulting in deep recursions in the code, such that after starting the debugging I have to step farther into the program manually. When this happens in a function func(obj a), I usually write some ugly code like this:
public void func(obj a) {
if(a instanceof someClass && ((someClass)a).hasSomeProperty() && ((someClass)a).getIdentifier().equals("myID")) {
// set a breakpoint here
}
// other code
}
So basically I try to identify the interesting situation by identifying an object that was passed to a function. I know these values because I usually have a breakpoint on an exception that is thrown in the other code. So my question is this: instead of writing all this ugly code to generate a proper breakpoint, is there a way to configure a conditional breakpoint based on some value that a variable has in a former debugging session? Basically say: halt here when the object is exactly like this one here?
You might do the following: write a static utility method ("writer") that serializes and writes the object you want to compare with a future debugging session; and another method ("reader") which receives an Object and compares it with the serialized version, returning true when both are equal.
After that, you can define one or more conditional breakpoints which call up the "writer" method and don't stop.
Additionally, you'd define another conditional breakpoint calling the "reader" method, which halts the thread as usual but only when the condition is met.
Netbeans offers the conditional breakpoint feature: after you set a breakpoint on a line you right click on it, choose Breakpoint-Properties, select the Condition checkbox and insert Java code to express a condition that must be true to break program execution.
add the breakpoint, right click it, go to breakpoint -> properties
at the breakpoint properties window you will see a condition box, and you add your if
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've seen this question but have a few more questions about the usage of the assert keyword. I was debating with a few other coders about using assert. For this use case, there was a method that can return null if certain prerequisites are met. The code I wrote calls the method, then asserts it doesn't return null, and continues to use the returned object.
Example:
class CustomObject {
private Object object;
#Nullable
public Object getObject() {
return (object == null) ? generateObject() : object;
}
}
Now imagine I use it like this:
public void useObject(CustomObject customObject) {
object = customObject.getObject();
assert object != null;
// Do stuff using object, which would throw a NPE if object is null.
}
I was told I should remove the assert, that they should never be used in production code, only be used in testing. Is that true?
Use Objects.requireNonNull(Object) for that.
Checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, [...]
In your case that would be:
public void useObject(CustomObject customObject) {
object = customObject.getObject();
Objects.requireNonNull(object); // throws NPE if object is null
// do stuff with object
}
This function is made for what you want to do: explicitly mark what is not to be null. The benefit is that you find null-values right where they should not occur. You will have less troubles debugging problems caused by nulls that are passed somewhere where they shouldn't be.
Another benefit is the flexibility when using this function in contrast to assert. While assert is a keyword for checking a boolean value, Objects.requireNonNull(Object) is a function and can be embedded in code much easier.
Foo foo = Objects.requireNonNull(service.fetchFoo());
// you cannot write it in one line.
Bar bar = service.fetchBar();
assert bar != null;
service.foo(Objects.requireNonNull(service.getBar()));
// you cannot write it in one line.
Bar bar = service.getBar();
assert bar != null;
service.foo(bar);
Keep in mind that Objects.requireNonNull(Object) is only for null-checking while assert is for general assertions. So assert has different purposes: primarily testing. It has to be enabled, so you can enable it for testing and disable it in production. Use it to seperate testing-only-tests from tests, or rather checks, that are meant for production-code too.
The most important thing to remember about assertions is that they can be disabled, so never assume they'll be executed.
For backward compatibility, the JVM disables assertion validation by default. They must be explicitly enabled using either the -enableassertions command line argument, or its shorthand -ea:
java -ea com.whatever.assertion.Assertion
So, it's not a good practice to rely on them.
As assertions aren't enabled by default you can never assume they will be executed when used in the code. So you should always check for null values and empty Optionals, avoid using assertions to check inputs into a public method and instead use an unchecked exception... In general do all the checks as if the assertion wasn't there.
Surely what you are told is a blatant lie. Here's why.
Assertions are disabled by default if you just execute standalone jvm. When they are disabled, they have zero footprint, hence they will not affect your production application. However, they are probably your best friends when developing and testing your code, and most of testing framework runners enable assertions (JUnit does), so your assertion code is executed when you run your unit tests, helping you detect any potential bugs earlier (e.g. you can add asserts for some business logic boundary checks, and that will help detect some code which uses inappropriate values).
That said, as the other answer suggests, for exactly that reason (they are not always enabled) you cannot rely on assertions to do some vital checks, or (especially!) maintain any state.
For an interesting example of how you could use asserts, have a look here - at the end of the file there's a method singleThreadedAccess() which is called from the assert statement on line 201 and is there to catch any potential multithreaded access in tests.
The other answers already cover this well enough, but there are other options.
For example, Spring has a static method:
org.springframework.util.Assert.notNull(obj)
There are other libraries with their own Assert.something() methods as well. It's also pretty simple to write your own.
However, keep in mind what exceptions you throw if this is a web service. The previous method mentioned, for example, throws an IllegalArgumentException which by default in Spring returns a 500.
In the case of a web service, this is often not an internal server error, and should not be a 500, but rather a 400, which is a bad request.
Use asserts liberally whenever doing so helps catching programming mistakes i.e. bugs.
Do not use assert to catch something that might logically happen i.e. badly formatted input. Use assert only when the error is unrecoverable.
Do not put any production logic in the code that runs when the assertion is checked. If your software is well written this is trivially true but if it's not then you might have subtle side effects and different overall behavior with assertions enabled and disabled.
If your company has "testing code" and "production code" doing the same thing but as different code bases (or different stages of editing), get out of there and never come back. Trying to fix that level of incompetence is probably a waste of your time.
If your company doesn't put any assert statement outside of the code of the tests, kindly tell them that asserts are disabled in the production build and that if they aren't, fixing that mistake is now your first priority.
The value of asserts is precisely to be used inside the business logic and not only the test suite.
This makes it easy to churn out many high level tests that don't have to explicitly test many things to go through big chunks of your code and trigger all these assertions.
In a few of my projects typical tests didn't even really assert anything, they just ordered a calculation to happen based on specific input and this caused hundreds of assertions to be checked and problems to be found even in tiny pieces of logic deep down.
You can use assert any time. The debate come is when to use. For example in the guide :
Do not use assertions for argument checking in public methods.
Do not use assertions to do any work that your application requires for correct operation.
A common problem I face when debugging recursive methods is that I can't avoid getting trapped into going deeper and deeper into the stack when I want to debug a given piece of code. The only way to avoid getting trapped is to manually disable the BP and then set up it again after the block of code I'm interested in has been passed.
In the above picture, I just want to do a little stroll over the loop's variables for each iteration, seeing if they're behaving as they should and if all's fine and dandy, but I'm currently only getting the first iteration of each call to combinations!
Any clever ideas to get around this?
Try to use conditional breakpoint if you want to hit the breakpoint only for some condition or for ith recursion depth. If you want to unwind recursion, after some of your testing/validation, while debugging you can change the value of the base condition variable from eclipse debugger.
If you have the ability to modify the recursive method I often do this sort of thing.
int combinations(int, a1, int a2) {
return(combinationsImpl(a1,a2,0));
}
int combinationsImpl(int, a1, int a2, int level) {
if(done) {
// on done
return(value);
}
// you can use level to do conditional break points, prints etc
// you can save the value when it crashes or throws an exception etc
// if you need to see variables in the stack log the level and the variables
// to console or a file and then see on what level values become anomalous etc.
return(combinationsImpl(a1,a2,++level));
}
As part of my AP curriculum I am learning java and while working on a project I wondered which of the following is best way to return a value?
public double getQuarters(){
return quarters;
}
or
public void getQuarters(){
System.out.println(quarters);
}
***Note: I now that the second option is not "technically" returning a value but its still showing my the value so why bother?
Your answer would be correct. The second method doesn't return any value at all, so while you might be able to see the output, your program can't. The second method could still be useful for testing or even for a command line application, but it should be named something like printQuarters instead.
public double getQuarters(){
return quarters;
}
Use this incorder to encapsulate quarters and hide it from being accessed by other programs. That means, you have to declare it as private quarters. Let see the second option:
public void getQuarters(){
System.out.println(quarters);
}
However, this seems wrong as getQuarters is not returning anything. Hence it would make more sense to refactor it as
public void printQuarters(){
System.out.println(quarters);
}
You answered your own question. For most definitions of the word "best", you should go with the first option.
Your question, however, does touch on the object-oriented programming topic of accessors and mutators. In your example, "getQuarters" is an accessor. It is usually best to use accessors to retrieve your values. This is one way to adhere to the Open/Closed Principle.
Also, the Java community has a coding convention for this and many tools and libraries depend on code following those conventions.
If all you need to do is display the value when this method is called, and you are ok with console output, then your System.out.println method will do the job. HOWEVER, a function that actually returns the variable is much more semantically correct and useful.
For example, while you may only need to print the variable for your current project, what if you came back later and decided that you were instead going to output your variable to a file? If you wrote your getQuarters function with a println statement, you would need to rewrite the whole thing. On the other hand, if you wrote the function as a return, you wouldn't need to change anything. All you'd have to do is add new code for the file output, and consume the function where needed.
A returning function is therefore much more versatile, although more so in larger code projects.
You return values to a specific point in your program, so that the program can use it to function.
You print values at a specific point in your program, so that you as an end user can see what value you got back for some function.
Depending on the function - for instance, yours - the result of quarters is no longer regarded in the program; all it did was print a value to the screen, and the application doesn't have a [clean|easy] way to get that back to use it.
If your program needs the value to function, then it must be a return. If you need to debug, then you can use System.out.println() where necessary.
However, more times than not, you will be using the return statement.
Option 1 is far superior.
It can be easily Unit Tested.
What if the spec changes and sometimes you want to print the result, other times put it into a database? Option 1 splits apart the logic of obtaining the value from what to do with it. Now, for a single method getQuarters no big deal, but eventually you may have getDimes, getEuros, etc...
What if there may be an error condition on quarters, like the value is illegal? In option 1, you could return a "special" value, like -1.0, or throw an Exception. The client then decides what to do.
public static void main(String args[])
{
if(true)
{
int x= 3*44+7;
//int y=1;
}
}
I narrowed my problem to this simple statement and I dont really know how this variable can be accessed in the eclipse debugger. It always happens in situations where a variable is declared in a if condition, try-catch statement, loops, etc and is accidentally the last statement in that block.
To solve this issue i stop my debugging session, add another statement to that block, redo everything I just did. Is there a better solution?
You are right, the it is hard to see the value of the last statement: when you pass the last line the program terminates.
The workaround can be either to add dummy line after this statement and put breakpoint there or to use "Expressions" view and put expression of x (i.e. 3*44+7) there.
BTW please pay attention that this is not a typical case in real world where programs are a little bit longer than 1 executable line. :)
The last "statement" is run, it's simply that you can't see the variable result because:
The variable doesn't exist before this statement.
The variable doesn't exist while the statement is being executed - the last step is to assign the resulting value to the variable.
The variable would have existed on the next line, but that line ends the scope that the variable is declared in, so the variable no longer exists.
In a more "real world" example, you could do something like this -
Change:
public int doIt() {
return 3*44+7;
}
To:
public int doIt() {
int x = 3*44+7;
return x;
}
And set the breakpoint on the 'return' line.
In your situation the compiler might actually remove the assignment, as the variable x is never used later on.
Anyways... one workaround you can use in your debugger, (assuming the statement you wish to debug is not state changing) would be to use the scrapbook, or to use inspect.
http://www.ibm.com/developerworks/library/os-ecbug/ figures 7 and 8
you can highlight an expression (part of a statement or entire statement) and inspect I believe. (haven't used eclipse in a few months). the alternative is to stop at the line (so before the expression triggers) and copy the line into your display view, and run it there.
it will run within the current stackframe, so all your local objects are available.
however , running set and other state changing calls will actually change the state of your program. (it's not ideal but it beats stopping the debugger)
I can't see any solution to your problem.
Since you can only see variables defined before your current line, you obviously need a statement after your variable declaration.
If there's no statement, your variable is not in current scope anymore (in your case, your program ends) and thus cannot be queried.
BTW, you said that you stopped your debugging session. With HotSwap, you could have dynamically replace current method's code and restart your debug at the beginning of the method (see 'Drop to frame' in your debugger)
If I get a NullPointerException in a call like this:
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
I get a rather useless exception text like:
Exception in thread "main" java.lang.NullPointerException
at package.SomeClass.someMethod(SomeClass.java:12)
I find it rather hard to find out which call actually returned null, often finding myself refactoring the code to something like this:
Foo ret1 = someObject.getSomething();
Bar ret2 = ret1.getSomethingElse();
Baz ret3 = ret2.getAnotherThing();
Bam ret4 = ret3.getYetAnotherOject();
int ret5 = ret4.getValue();
and then waiting for a more descriptive NullPointerException that tells me which line to look for.
Some of you might argue that concatenating getters is bad style and should be avoided anyway, but my Question is: Can I find the bug without changing the code?
Hint: I'm using eclipse and I know what a debugger is, but I can't figuer out how to apply it to the problem.
My conclusion on the answers:
Some answers told me that I should not chain getters one after another, some answers showed my how to debug my code if I disobeyed that advice.
I've accepted an answer that taught me exactly when to chain getters:
If they cannot return null, chain them as long as you like. No need for checking != null, no need to worry about NullPointerExceptions (be warned that chaining still violates the Law of Demeter, but I can live with that)
If they may return null, don't ever, never ever chain them, and perform a check for null values on each one that may return null
This makes any good advice on actual debugging useless.
NPE is the most useless Exception in Java, period. It seems to be always lazily implemented and never tells exactly what caused it, even as simple as "class x.y.Z is null" would help a lot in debugging such cases.
Anyway, the only good way I've found to find the NPE thrower in these cases is the following kind of refactoring:
someObject.getSomething()
.getSomethingElse()
.getAnotherThing()
.getYetAnotherObject()
.getValue();
There you have it, now NPE points to correct line and thus correct method which threw the actual NPE. Not as elegant solution as I'd want it to be, but it works.
The answer depends on how you view (the contract of) your getters. If they may return null you should really check the return value each time. If the getter should not return null, the getter should contain a check and throw an exception (IllegalStateException?) instead of returning null, that you promised never to return. The stacktrace will point you to the exact getter. You could even put the unexpected state your getter found in the exception message.
In IntelliJ IDEA you can set exceptionbreakpoints. Those breakpoints fire whenever a specified exception is thrown (you can scope this to a package or a class).
That way it should be easy to find the source of your NPE.
I would assume, that you can do something similar in netbeans or eclipse.
EDIT: Here is an explanation on how to add an exceptionbreakpoint in eclipse
If you find yourself often writing:
a.getB().getC().getD().getE();
this is probably a code smell and should be avoided. You can refactor, for example, into a.getE() which calls b.getE() which calls c.getE() which calls d.getE(). (This example may not make sense for your particular use case, but it's one pattern for fixing this code smell.)
See also the Law of Demeter, which says:
Your method can call other methods in its class directly
Your method can call methods on its own fields directly (but not on the fields' fields)
When your method takes parameters, your method can call methods on those parameters directly.
When your method creates local objects, that method can call methods on the local objects.
Therefore, one should not have a chain of messages, e.g. a.getB().getC().doSomething(). Following this "law" has many more benefits apart from making NullPointerExceptions easier to debug.
I generally do not chain getters like this where there is more than one nullable getter.
If you're running inside your ide you can just set a breakpoint and use the "evaluate expression" functionality of your ide on each element successively.
But you're going to be scratching your head the moment you get this error message from your production server logs. So best keep max one nullable item per line.
Meanwhile we can dream of groovy's safe navigation operator
Early failure is also an option.
Anywhere in your code that a null value can be returned, consider introducing a check for a null return value.
public Foo getSomething()
{
Foo result;
...
if (result == null) {
throw new IllegalStateException("Something is missing");
}
return result;
}
Here's how to find the bug, using Eclipse.
First, set a breakpoint on the line:
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
Run the program in debug mode, allow the debugger to switch over to its perspective when the line is hit.
Now, highlight "someObject" and press CTRL+SHIFT+I (or right click and say "inspect").
Is it null? You've found your NPE. Is it non-null?
Then highlight someObject.getSomething() (including the parenthesis) and inspect it.
Is it null? Etc. Continue down the chain to figure out where your NPE is occurring, without having to change your code.
You may want to refer to this question about avoiding != null.
Basically, if null is a valid response, you have to check for it. If not, assert it (if you can). But whatever you do, try and minimize the cases where null is a valid response for this amongst other reasons.
If you're having to get to the point where you're splitting up the line or doing elaborate debugging to spot the problem, then that's generally God's way of telling you that your code isn't checking for the null early enough.
If you have a method or constructor that takes an object parameter and the object/method in question cannot sensibly deal with that parameter being null, then just check and throw a NullPointerException there and then.
I've seen people invent "coding style" rules to try and get round this problem such as "you're not allowed more than one dot on a line". But this just encourages programming that spots the bug in the wrong place.
Chained expressions like that are a pain to debug for NullPointerExceptions (and most other problems that can occur) so I would advise you to try and avoid it. You have probably heard that enough though and like a previous poster mentioned you can add break points on the actual NullPointerException to see where it occurred.
In eclipse (and most IDEs) you can also use watch expressions to evaluate code running in the debugger. You do this bu selecting the code and use the contet menu to add a new watch.
If you are in control of the method that returns null you could also consider the Null Object pattern if null is a valid value to return.
Place each getter on its own line and debug. Step over (F6) each method to find which call returns null