是“这个"吗?遮蔽一个好主意? [英] Is "this" shadowing a good idea?

查看:113
本文介绍了是“这个"吗?遮蔽一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,阴影类变量的情况很常见. Eclipse会很高兴地生成以下代码:

The case of shadowing class variables is common in in Java. Eclipse will happily generate this code:

public class TestClass {
    private int value;
    private String test;
    public TestClass(int value, String test) {
        super();
        this.value = value;
        this.test = test;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public String getTest() {
        return test;
    }
    public void setTest(String test) {
        this.test = test;
    }
}

可变阴影可以吗?

我正在考虑实施一条编码规则,该规则说不允许阴影".在上面的简单情况中,很清楚发生了什么.添加更多执行某些操作的代码,您将有丢失"this"并引入错误的风险.

I am considering the implementation of a coding rule saying that "shadowing will not be allowed." In the simple case above it is clear enough what is going on. Add in a little more code that does something and you run the risk of missing "this" and introducing a bug.

普遍共识是什么?禁止遮挡阴影,有时允许它遮挡还是让其滚动?

What is the general consensus? Ban shadowing, allow it sometimes, or let it roll?

推荐答案

我实际上更喜欢准则仅在构造函数和设置方法中使用阴影".不允许其他所有内容.
避免为命名构造函数自变量aValueaTest命名的麻烦,以免产生阴影.

I actually prefer the guideline "Shadowing is only allowed in constructors and setters". Everything else is not allowed.
Saves you the trouble of naming constructor arguments aValue and aTest just to avoid shadowing.

如果您使用的是eclipse,则其警告设置可以完全设置为该选项BTW.

If you're using eclipse, its warnings settings can be set exactly to that option BTW.

这篇关于是“这个"吗?遮蔽一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆