Say way have a variable (let's say String Str) and the value of Str starts of as " " then as some code is running it is set to "test" then somewhere else in the code it is changed again to say "tester". Now in the program I want to find out what the previous value of Str was. Is this possible in Java?
So I am saying that the variable gets changed twice, and you want to find out what Str was before it got changed for the second time. So in the example above the latest value of Str would be "tester" but I wanted to find out what Str was before this (assuming you had no idea what it was before it was changed to tester) in this case I would want to be able to find out that Str was "test".
Is it at all possible to do this in Java?
No, it's not possible, you have to save the previous value before you change it to do what you're asking for.
Not as a native part of the language, no. You could write a setter that saved the current (previous?) value when the String changes, though.
private String str;
private String prev;
setStr(String s)
{
prev = str;
str = s;
}
Then just write a separate getter for prev.
Of course, this solution relies on you always using the setter to change the value of str.
Also, as deworde points out, if your program doesn't need this information, then you shouldn't modify your program to save it. If you need the information for debugging purposes you can just set a watch in your IDE's debugger.
Simple answer, no.
However, you could use:
AOP
An AOP framwork, such as AspectJ could intercept assignments to a variable.
See AspectJ pointcut reference
JavaBeans Property Change Support
You could use standard JavaBean setters, getters to encapsulate your field. Then you can register listeners on a bean to listen out for property changes, and even veto that change.
See JavaBean Spec for more information.
Example listener:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class MyBeanListener implements PropertyChangeListener,
VetoableChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.printf("Notifed of property changed event: %s => %s%n", evt
.getOldValue(), evt.getNewValue());
}
#Override
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
System.out.printf("Notified of vetoable change event: %s => %s%n", evt
.getOldValue(), evt.getNewValue());
}
}
If you really have a strong need for this you could use the following code:
public class Main
{
public static void main(final String[] argv)
{
SavedValue<Integer> i;
i = new SavedValue<Integer>();
i.set(7);
System.out.println(i.get());
System.out.println(i.getOld());
}
}
class SavedValue<T>
{
private T oldValue;
private T value;
void set(final T val)
{
oldValue = value;
value = val;
}
T get()
{
return (value);
}
T getOld()
{
return (oldValue);
}
}
Perhaps you could explain why you want the old value? I am sure we can give you much better answers if we knew why yoiu wanted it.
You already got the two simple answers:
No, Java itself doesn't allow that
You can use setters and implement a mechanism to keep the old value(s)
But there is a third one which I haven't seen so far:
It should be possible to write an Aspect in AspectJ that triggers on the assignment. So it would have a similar effect as a setter, without the actual setter. If you are working with code that you don't want to or cannot change this might be an option.
Note that while AspectJ isn't Java the result is normal byte code, so it should be compatible with most environments.
Of course instead of using AspectJ you could do this with CGLIB.
It looks like you're using this for debugging, am I right?
Visual Studio, or any decent debugger should allow you to print a trace of the value every time it's set just by putting a "tracepoint" before and after all the calls that set the value.
You just alter the properties of a normal breakpoint to print a statement rather than halt execution.
In VS2005 this is done by:
Bringing up the breakpoint window
Right-clicking on the breakpoint
Selecting the option "When Hit...".
Selecting "Print a Message" and entering a message
Making sure that "Continue Execution" is still selected.
This normally slows the program down significantly while debugging, so it's of little use for time-dependent debugging; but it's still allowed me to follow a variable's states (ABCDFEGH...)
Of course, if you do want to halt execution, just dump a normal breakpoint in.
You may try to use a stack data structure. It will keep all previous values in the right order. You may implement your own or use the java Collections one:
Deque<Integer> stack = new ArrayDeque<Integer>();
Each time you set the variable, put it in the stack (either through setter or AOP as mentioned in the other answers).
That way, you will be able to access al previous values.
Indeed, this is not possible. You'd have to create your own String class that had some sort of memory to achieve this.
In addition to what Stefan said, I would recommend a List structure of some kind containing all the historical values.
When you want to change the value, just add a new value to the end of the list. When you want to get the current value, just look at the last value. If you want to see previous values, start from the end of the list.
If you could find the previous state of the program, there would never be any garbage to collect and the program would very quickly run out of memory.
For specific variables, you could use, say, a LIFO stack. Instead of an assignment you would push to the stack. Instead of reading the variable, you would peek. The contents of the stack can be examined to find historical values.
Another approach would be to use instrumentation. This allows you to, with sufficient skill and patience, rewrite byte code to do what ever you want.
Perhaps you want to stand back a bit and look at what you are actually trying to achieve.
I don't know the reasons for wanting to do this, but I'm guessing it's debugging of some kind.
If you're using eclipse, you can set breakpoints that trigger when a variable changes. That might achieve what I assume you're trying to get to.
This is in fact possible using something called a Historical Debugger, and it is accomplished by instrumenting the bytecode so that any assignment to the variable is recorded.
Gooogle Bil Lewis Historical Debugger for one example. Note that most of this software is in what you'd call an 'initial beta' phase.
Have you heard about Jive? It allows backward stepping in debug so this is partially answer to your question Read here: http://www.cse.buffalo.edu/jive/
Yes!! When you change the value, the value is changed only for the particular object. See the ex:
class Test{
int a=100; //original value
Test(int b){
this.a=b;
}
Test(){
}
void print(){
System.out.println(a);
}
public static void main(String args[]){
Test t=new Test(9);
Test t2=new Test();
t.print(); //output: 9
t2.print(); //output: 100
}
}
Related
I'm learning how to code in Java. I'm a little confused by "return;" and what it does and when we use it. Please see the following example of code:
public int something() {
return 1;
}
public static void main() {
int returnValue = something();
System.out.println(returnValue);
//Prints 1
}
Why wouldn't we just store 1 into a int variable called something then use System.out.print(something);
When would we use the return method instead of simply storing into a variable?
Thank you
Sure you could store into a variable but then you would lose one of the very important features, namely the ability to call the method inside itself.
This is relevant for algorithms that divide the work into smaller chunks and invoke themselves on the smaller chunks (and then combine the individual result to a big result). This is very common in sorting algorithms. The technical term is recursion.
Usually the compiler actually does exactly this; creates a variable for storing the value from where the calling code can pick it up. This variable is typically put in the same location - the stack - as the parameters passed in to the called method, and is invisible to your code.
(Also it is needed to make it threadsafe which is essential to utilizing more than one core on a modern cpu).
I know how to set a watchpoint for a field (right click variable in variables view -> watch). But the execution pauses on access/modification of that field of ALL objects of that type.
How can one just pause execution when a certain field of a SPECIFIC OBJECT is accessed or modified?
To make it more clear:
class A { int a; }
public static void main(String[] args) {
List<A> myList = new ArrayList<A>();
// assume a lot of A's are added here
A interestingA = new A();
myList.add(someIndex, interestingA);
for(A a : myList) {
a.a = 42; // debugger shall stop here, but only,
// if it is the interesting A
}
}
Obviously I cannot set a breakpoint there, because I would have to click on continue a lot of times. Furthermore, interestingA may be modified from other spots I am not aware of and in that case debugger should stop too.
You need a way to identify which instance you want to debug. Then you can add a condition to the breakpoint.
For example,
class A
{
int a;
final String name;
public A(final String name)
{ this.name = name; }
}
public static void main(String[] args) {
A a1 = new A("foo");
A a2 = new A("bar");
a1.a = 42; // debugger shall not stop here
a2.a = 42; // but here, because I am interested in object a2
}
Then put "bar".equals(name) as the condition on your breakpoint.
http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fbreakpoints%2Fref-condition_option.htm
https://wiki.eclipse.org/FAQ_How_do_I_set_a_conditional_breakpoint%3F
https://stackoverflow.com/a/7194409/1172714
Define the problem
I would have to say that this is actually two problems; first how to get Eclipse to stop but only when a variable changes, and second where to place the breakpoints that use the technique from point one.
Like other links listed in other answers, my answer to this question has the details on the "how" part but not the "where" part.
Suggest a solution
You might have you use the 'find all references' giving you the places in the code that refer to the variable and place breakpoints at those lines and in each one include the conditional expression. This is a bit brute-force but at least Eclipse can do the hard part (the semantic search) for you.
Commentary
As an aside, I've been wanting the feature you are describing for many many years. I'm sure I'm not the only programmer who discovers that some logic is failing because a certain variable doesn't have the correct value but can't figure out where the value is getting changed. I don't believe there is a good answer to this problem without introducing a new type of breakpoint in Eclipse which halts execution anywhere based on a variable changing. Just typing that makes me realize how inefficient that would be because the variable would have to be evaluated after every JVM instruction which I suspect would make debugging become so CPU-bound as to be useless.
Following is an example code , checkUserGuess method that belongs to a Board class.
public String checkUserGuess(String aGuess)
{
// Some processing
return result_of_a_guess;
}
I have a SimpleGuessingGame class consumes this method and is satisfied with the processing that the method does. It does not use the returned value.
Another class ComplexGuessingGame consumes this method and also uses the value returned by the method for further processing.
So we have two cases , one where the return value is used and other where its ignored. Is this a common occurrence or does this point to bad design ?
When you need to do something like this, chances are that the method does two things that are of value to a caller:
Validates something, or produces another side effect, and
Computes the result to be returned to the callers
Since some users need only #1, while other users need both #1 and #2, it may be a good idea to split the method in two parts, like this:
public void validatekUserGuess(String aGuess) {
// Some processing
}
public String checkUserGuess(String aGuess) {
validatekUserGuess(aGuess);
// Some additional processing
return result_of_a_guess;
}
Now the users that wish to ignore the return value would not be required to "pay" with CPU and memory for computing a value that they are going to discard anyway.
There is nothing inherently wrong with using a return value in one call, and not using it in another.
Imagine in one case you want to attempt to turn a light on, and in another you want to make sure it was actually turned on.
public boolean turnOn(Light l);
case 1:
turnOn(new Light());
log.debug("Attempted to turn on light");
case 2:
boolean turnedOn = turnOn(new Light());
if (turnedOn) {
log.debug("Light is turned on");
} else {
log.debug("Not able to turn light on");
}
If the two are exactly identical (and the result_of_a_guess is needed but just not returned) then I would say that you are fine. Many times built-in functions have return values that people ignore because they just don't need them (but they are nice to have for extra processing, like you seem to be doing).
If you really don't like the return value then you can place result_of_a_guess in a member variable to be only set when the checkUserGuess is flagged as complex like so:
public void checkUserGuess(String aGuess, Boolean isComplex)
{
// Some processing
if (isComplex)
setResult(result_of_a_guess)
}
I've seen a lot of both. In my opinion it comes down to a stylistic choice/ preference. You need to know and understand the scope of your project and what works best for you and your future code!
I found this little gem in our codebase at work recently. I have to confess that I have absolutely no idea why this enum was written in this way (names changed to protect the innocent):
package foo.bar;
import sun.misc.SharedSecrets;
import foo.baz.HasAGetValuesMethod;
public enum MysteryEnum implements HasAGetValuesMethod {
THINGY, BOB;
#Override
public MysteryEnum[] getValues() {
return SharedSecrets.getJavaLangAccess().getEnumConstantsShared(MysteryEnum .class);
}
}
In the getValues() method instead of simply calling MysteryEnum.values() it's using something called sun.misc.SharedSecret to get a handle to something called sun.misc.JavaLangAccess, then using that to get an array of all the enum values. The Javadoc on that class tells you what the method does, but I can't find much on why you would want to call it.
The developer that wrote this is no longer around, so I can't ask him. I'm going to ask my team anyway, but I have a feeling that the answer will be: "Don't know why it does that, but better not change it". For the moment, I'm assuming that this is either an odd case of someone not knowing that the values() method exists, or that my ignorance of the sun.misc libraries is causing me to miss something obvious to others. Any idea's why this code was written this way?
The method returns the same array without reflection or copying/cloning the underlying array. This improves performance, but is not a good idea to exposes a mutable array.
for (int i = 0; i < 3; i++)
System.out.println(SharedSecrets.getJavaLangAccess().getEnumConstantsShared(AccessMode.class));
AccessMode[] ams = SharedSecrets.getJavaLangAccess().getEnumConstantsShared(AccessMode.class);
ams[1] = ams[2]; // don't do this !!
System.out.println(EnumSet.allOf(AccessMode.class));
prints
[Ljava.nio.file.AccessMode;#330cdec1
[Ljava.nio.file.AccessMode;#330cdec1
[Ljava.nio.file.AccessMode;#330cdec1
[READ, EXECUTE, EXECUTE]
Instead of using this method, what I do is use my own cached copy
// cannot be modified.
private static final AccessMode[] ACCESS_MODES = AccessMode.values();
Basically SharedSecret:
A repository of "shared secrets", which are a mechanism for
calling implementation-private methods in another package without
using reflection.
The code returns the enum constants by reading the class and returning the constants back (without needing to do reflection calls). This is dynamic in a way that if a new enum constant is added to the enum, the getValues() method will return the added enums (no need to change code all over the show).
The documentation says:
Returns the elements of an enum class or null if the Class object does
not represent an enum type; the result is uncloned, cached, and shared
by all callers.
So, unless the point was to provide a shared array, so that anyone could break everything by setting one of its elements to null, or sorting it, or whatever (which could have been done by caching the result of the values() method), my guess is also that this line is there due to the incompetence of the previous developer.
I would write a unit test, then replace it with a call to values() and check that the unit test still passes.
Just for information:
I was looking into the implementation of EnumMap and found the same code snippet where all enum values are fetched from the class name.
/**
* Returns all of the values comprising K.
* The result is uncloned, cached, and shared by all callers.
*/
private static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
return SharedSecrets.getJavaLangAccess()
.getEnumConstantsShared(keyType);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
OK, after reviewing some code with PMD and FindBugs code analyzers, i was able to do great changes on the reviewed code. However, there are some things i don't know how to fix. I'll iterate them bellow, and (for better reference) i will give each question a number. Feel free to answer to any/all of them. Thanks for your patience.
1. Even tough i have removed some of the rules, the associated warnings are still there, after re-evaluate the code. Any idea why?
2. Please look at the declarations :
private Combo comboAdress;
private ProgressBar pBar;
and the references to objects by getters and setters :
private final Combo getComboAdress() {
return this.comboAdress;
}
private final void setComboAdress(final Combo comboAdress) {
this.comboAdress = comboAdress;
}
private final ProgressBar getpBar() {
return this.pBar;
}
private final void setpBar(final ProgressBar pBar) {
this.pBar = pBar;
}
Now, i wonder why the first declaration don't give me any warning on PMD, while the second gives me the following warning :
Found non-transient, non-static member. Please mark as transient or provide accessors.
More details on that warning here.
3. Here is another warning, also given by PMD :
A method should have only one exit point, and that should be the last statement in the method
More details on that warning here.
Now, i agree with that, but what if i write something like this :
public void actionPerformedOnModifyComboLocations() {
if (getMainTree().isFocusControl()) {
return;
}
....//do stuffs, based on the initial test
}
I tend to agree with the rule, but if performance of the code suggest multiple exit points, what should i do?
4. PMD gives me this :
Found 'DD'-anomaly for variable 'start_page' (lines '319'-'322').
when i declare something like :
String start_page = null;
I get rid of this info (level of warning is info) if i remove the assignment to null, but..i got an error from IDE, saying that the variable could be uninitialized, at some point later in the code. So, i am kind of stuck with that. Supressing the warning is the best you can do?
5. PMD Warning :
Assigning an Object to null is a code smell. Consider refactoring.
This is the case of a singletone use of GUI components or the case of a method who returns complex objects. Assigning the result to null in the catch() section it's justified by the need to avoid the return of an incomplete/inconsistent object. Yes, NullObject should be used, but there are cases where i don't want to do that. Should i supress that warning then?
6. FindBugs warning #1:
Write to static field MyClass.instance from instance method MyClass.handleEvent(Event)
in the method
#Override
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Dispose: {
if (e.widget == getComposite()) {
MyClass.instance = null;
}
break;
}
}
}
of the static variable
private static MyClass instance = null;
The variable allows me to test whether the form is already created and visible or not, and i need to force the re-creation of the form, in some cases. I see no other alternative here. Any insights? (MyClass implements Listener, hence the overrided handleEvent() method).
7. FindBugs warning #2:
Class MyClass2 has a circular dependency with other classes
This warning is displayed based on simple imports of other classes. Do i need to refactor those imports to make this warning go away? Or the problem relies in MyClass2?
OK, enough said for now..expect an update, based on more findings and/or your answers. Thanks.
Here are my answers to some of your questions:
Question number 2:
I think you're not capitalizing the properties properly. The methods should be called getPBar and setPBar.
String pBar;
void setPBar(String str) {...}
String getPBar() { return pBar};
The JavaBeans specification states that:
For readable properties there will be a getter method to read the property value. For writable properties there will be a setter method to allow the property value to be updated. [...] Constructs a PropertyDescriptor for a property that follows the standard Java convention by having getFoo and setFoo accessor methods. Thus if the argument name is "fred", it will assume that the reader method is "getFred" and the writer method is "setFred". Note that the property name should start with a lower case character, which will be capitalized in the method names.
Question number 3:
I agree with the suggestion of the software you're using. For readability, only one exit point is better. For efficiency, using 'return;' might be better. My guess is that the compiler is smart enough to always pick the efficient alternative and I'll bet that the bytecode would be the same in both cases.
FURTHER EMPIRICAL INFORMATION
I did some tests and found out that the java compiler I'm using (javac 1.5.0_19 on Mac OS X 10.4) is not applying the optimization I expected.
I used the following class to test:
public abstract class Test{
public int singleReturn(){
int ret = 0;
if (cond1())
ret = 1;
else if (cond2())
ret = 2;
else if (cond3())
ret = 3;
return ret;
}
public int multReturn(){
if (cond1()) return 1;
else if (cond2()) return 2;
else if (cond3()) return 3;
else return 0;
}
protected abstract boolean cond1();
protected abstract boolean cond2();
protected abstract boolean cond3();
}
Then, I analyzed the bytecode and found that for multReturn() there are several 'ireturn' statements, while there is only one for singleReturn(). Moreover, the bytecode of singleReturn() also includes several goto to the return statement.
I tested both methods with very simple implementations of cond1, cond2 and cond3. I made sure that the three conditions where equally provable. I found out a consistent difference in time of 3% to 6%, in favor of multReturn(). In this case, since the operations are very simple, the impact of the multiple return is quite noticeable.
Then I tested both methods using a more complicated implementation of cond1, cond2 and cond3, in order to make the impact of the different return less evident. I was shocked by the result! Now multReturn() is consistently slower than singleReturn() (between 2% and 3%). I don't know what is causing this difference because the rest of the code should be equal.
I think these unexpected results are caused by the JIT compiler of the JVM.
Anyway, I stand by my initial intuition: the compiler (or the JIT) can optimize these kind of things and this frees the developer to focus on writing code that is easily readable and maintainable.
Question number 6:
You could call a class method from your instance method and leave that static method alter the class variable.
Then, your code look similar to the following:
public static void clearInstance() {
instance = null;
}
#Override
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Dispose: {
if (e.widget == getComposite()) {
MyClass.clearInstance();
}
break;
}
}
}
This would cause the warning you described in 5, but there has to be some compromise, and in this case it's just a smell, not an error.
Question number 7:
This is simply a smell of a possible problem. It's not necessarily bad or wrong, and you cannot be sure just by using this tool.
If you've got a real problem, like dependencies between constructors, testing should show it.
A different, but related, problem are circular dependencies between jars: while classes with circular dependencies can be compiled, circular dependencies between jars cannot be handled in the JVM because of the way class loaders work.
I have no idea. It seems likely that whatever you did do, it was not what you were attempting to do!
Perhaps the declarations appear in a Serializable class but that the type (e.g. ComboProgress are not themselves serializable). If this is UI code, then that seems very likely. I would merely comment the class to indicate that it should not be serialized.
This is a valid warning. You can refactor your code thus:
public void actionPerformedOnModifyComboLocations() {
if (!getMainTree().isFocusControl()) {
....//do stuffs, based on the initial test
}
}
This is why I can't stand static analysis tools. A null assignment obviously leaves you open to NullPointerExceptions later. However, there are plenty of places where this is simply unavoidable (e.g. using try catch finally to do resource cleanup using a Closeable)
This also seems like a valid warning and your use of static access would probably be considered a code smell by most developers. Consider refactoring via using dependency-injection to inject the resource-tracker into the classes where you use the static at the moment.
If your class has unused imports then these should be removed. This might make the warnings disappear. On the other hand, if the imports are required, you may have a genuine circular dependency, which is something like this:
class A {
private B b;
}
class B {
private A a;
}
This is usually a confusing state of affairs and leaves you open to an initialization problem. For example, you may accidentally add some code in the initialization of A that requires its B instance to be initialized. If you add similar code into B, then the circular dependency would mean that your code was actually broken (i.e. you couldn't construct either an A or a B.
Again an illustration of why I really don't like static analysis tools - they usually just provide you with a bunch of false positives. The circular-dependent code may work perfectly well and be extremely well-documented.
For point 3, probably the majority of developers these days would say the single-return rule is simply flat wrong, and on average leads to worse code. Others see that it a written-down rule, with historical credentials, some code that breaks it is hard to read, and so not following it is simply wrong.
You seem to agree with the first camp, but lack the confidence to tell the tool to turn off that rule.
The thing to remember is it is an easy rule to code in any checking tool, and some people do want it. So it is pretty much always implemented by them.
Whereas few (if any) enforce the more subjective 'guard; body; return calculation;' pattern that generally produces the easiest-to-read and simplest code.
So if you are looking at producing good code, rather than simply avoiding the worst code, that is one rule you probably do want to turn off.