Soy*_*yuz 8 java coding-style readability this
您不需要在Java中编写"this"关键字.但无论如何这样做会更好吗?将你的风格同质化是否有意义,即如果你使用"this"一次,你每次使用它时都会使用它?或者有一个地方,你总是会使用它和其他你从未使用它的地方?
Old*_*eon 19
普遍的共识是,您应该this只在必要时才使用,而不是在任何其他时间使用.
private String param;
public Construct(String param) {
// Usually the only place you need to use this.
this.param = param;
}
// A less common use of this
public Function() {
synchronized(this) {
// Some synchronized stuff.
}
}
Run Code Online (Sandbox Code Playgroud)
作为一项规则,我倾向于不使用它 - 如果你可以减少冗余代码,那就更好了.
但是,我可以想到有三个地方可以避免使用此关键字:
构造函数(委托给同一个类中的另一个构造函数)
public MyClass() {
this("Default Parameter");
Run Code Online (Sandbox Code Playgroud)同步当前对象
synchronized(this) {
将当前对象传递给另一个类
public void methodOne() {
anotherClass.doSomething(this);
Run Code Online (Sandbox Code Playgroud)有时你需要在构造函数中使用它,其中字段名称与参数相同,但这不是必须的,因为你可以简单地重命名参数:
public MyClass(String data) {
this.data = data
Run Code Online (Sandbox Code Playgroud)
除了这些我不能想到太多其他我使用this关键字的场景.我已经看到它过度使用(在每个方法和字段引用上),这可能使代码很难阅读.
只有在必要时或者当您认为它增强了代码可读性时才使用它.
| 归档时间: |
|
| 查看次数: |
2125 次 |
| 最近记录: |