我正在阅读本网站的教程。 http://tutorials.jenkov.com/java-unit-testing/matchers.html 作者我相信是非常有经验的。我看到了这样的代码。我还看到有人总是喜欢将方法的参数赋值给变量,然后在方法中使用它。这一条是这条线。 protected Object theExpected = expected;
将参数分配给其他变量有什么好处
谁能告诉我,什么是这种编码风格好处?这是否试图避免对象状态被改变或什么?
如果参数不是一个对象而是一个基本变量会怎么样?
如果它是一个像String这样的不可变Object。谢谢。
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());
}
};
}
这里是更新
我只是做了另外一个测试,看看这个参数仍然可以访问后,我们得到的对象。
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;
}
};
}
}
输出:
Here we go
Here we go
那么,这是否意味着,即使我们不指定这个参数设置为一个局部变量它仍然有效?
嗨@henry,我只是做了一个小测试,证明你是对的吗? – 2015-02-11 15:55:11