最近我得到了一个代码审查注释,使用getter方法访问同一类方法中的私有实例变量.这真的是一个好习惯吗?我觉得它在代码中添加了不必要的复杂功能.推荐的方式是什么?
public class SomeClass {
String abc;
public boolean compare(SomeClass otherClass) {
otherClass.getAbc().equals(abc);
}
}
public class SomeClass {
String abc;
public boolean compare(SomeClass otherClass) {
otherClass.getAbc().equals(getAbc());
}
}
Run Code Online (Sandbox Code Playgroud) 我写了一个方法,它在 try 语句中返回一些值。在 catch 中,我调用了 handleException,它将具有理解异常并重新抛出新异常的转换逻辑。这里 handleException 总是抛出异常, getXYZ() 仍然给出编译时错误,期望返回语句。我没有处理异常,我只是抛出新的异常,所以为什么该方法需要返回语句。
public String getXYZ(String input) {
try {
return getFromDAO(input);
} catch (Exception e) {
handleException(e);
}
}
private void handleException(Exception e) {
try {
throw e;
} catch(SomeException se) {
throw new MyRuntimeException("MyException message", se);
} catch(SomeOtherException soe) {
throw new MyRuntimeException("MyException message", soe);
}
}
Run Code Online (Sandbox Code Playgroud)
此方法的另一个版本编译。
public String getXYZ(String input) {
try {
return getFromDAO(input);
} catch (Exception e) {
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)