-4

您认为 Java 中有哪些好的编程实践?

我问这个问题的原因是:

我总是想知道我是否以错误的方式做事,所以我想了解更多关于良好做法的信息。

我总是困惑的一件事:

我是否应该总是使用this.xxx引用实例变量以将它们与局部变量区分开来?

4

5 回答 5

2

There are several ways to look at 'good coding practices'

  • Coding styles/idioms that is less prone to errors and guard against introducing new errors, thus leading to 'correct' code
  • Coing styles/idioms that are easier for others to read and maintain

In the first case, programmers adopt certain styles to guard themselves against introducing 'accidental' errors that can sneak into their code:

for Example in C, the following code is valid (but has a subtle bug)

if (x = 1)  // always evaluates to 'true' (programmer meant '==', not '=')
{
   // do something
}

so, in order to force the compiler to catch this error, you could adopt a style such as

if (1 == x) // if you accidentally typed '1 = x' the compiler will flag an error
{
   // do something 
}

Such styles/idioms are regarded as 'good' practices and there a quite a few that can be found for Java in books like 'Clean Code: A Handbook of Agile Software Craftsmanship (Robert C. Martin'

Regarding the second case, writing 'this.xxx' enables the reader of the code to differentiate between a local/instance variable, so in the spirit of code readability, it is marginally better than directly referencing the variable as 'xxx'.

于 2012-12-01T10:40:28.887 回答
0

我的建议是this在有助于解决潜在歧义时使用。 this.当您需要使用成员变量而不是同名的本地方法参数时需要。

使用 whwn 的情况是这样的:

public class ravi {

    public int x;
    public static float y;    

    public float getX(int x) {
        return this.x;
    }
于 2012-12-01T10:24:51.387 回答
0

this.xxx问题而言,是的,这是区分的一种方法。另一种方法是让局部变量以'p'为前缀,表示它是一个方法参数,这样你就可以实现这样的效果:

public void setField(Field pField) {
    field = pField; // instead of this.field = field, assuming field was the method argument.
}
于 2012-12-01T10:25:53.137 回答
0

如果您选择参数名称的拼写方式与您的类成员完全相同,我只会在构造函数和 setter 函数中使用 this.xx 进行赋值。例如:

public void setName(String name)
{
     this.name = name;
}

这是为了将您的类的名称成员与参数名称区分开来。

在一个类中,不要写 this.xxx(尽管在语法上仍然是正确的),特别是如果你只想获得它的值。例如,以下是“丑陋的”:

public String getFullName()
{
     return this.firstName + " " + this.lastName;
}

只需返回 firstName + " " + lastName; 这样写的少。

你会遇到比是否写 this.xxx 更重要的决定,比如是否使用内联函数或将它们作为类的单独函数,或者决定一个类是“是”还是“有”班级。

于 2012-12-01T14:09:50.450 回答
0

对于一般编码约定,这是一本好书:Java 风格元素http://www.ambysoft.com/books/elementsJavaStyle.html

于 2012-12-01T14:01:47.033 回答