I am reading a tutorial form this site.http://tutorials.jenkov.com/java-unit-testing/matchers.html
The author I believe is very experienced. I saw the code like this. I also saw someone else always like to assign the parameter of a method to a variable then use it inside the method. This one here is this line. protected Object theExpected = expected;
Can anyone please tell me, what is the benefit of this coding style? Is this trying to avoid the object status being changed or something?
What if the parameter is not an Object but a primitive variable.
And what if it is a immutable Object like String. Thank you.
public static Matcher matches(final Object expected){
return new BaseMatcher() {
protected Object theExpected = expected;
public boolean matches(Object o) {
return theExpected.equals(o);
}
public void describeTo(Description description) {
description.appendText(theExpected.toString());
}
};
}
Here is the update
I just did another test, to see if this parameter still accessible after we got the object.
package myTest;
public class ParameterAssignTest {
public static void main(String[] args) {
MyInterface myClass = GetMyClass("Here we go");
System.out.println(myClass.getValue());
System.out.println(myClass.getParameter());
}
public static MyInterface GetMyClass(final String myString){
return new MyInterface() {
protected String stringInside = myString;
@Override
public String getValue() {
return stringInside;
}
@Override
public String getParameter() {
return myString;
}
};
}
}
Output:
Here we go
Here we go
So does this mean that even we do assign this parameter to the a local variable it still works?