Are there any reasons not to use “this” (“Self”, “

2020-08-21 04:56发布

I read this answer and its comments and I'm curious: Are there any reasons for not using this / Self / Me ?

BTW: I'm sorry if this has been asked before, it seems that it is impossible to search for the word this on SO.

15条回答
【Aperson】
2楼-- · 2020-08-21 05:31

well, eclipse does color fields, arguments and local variables in different colors, so at least working in eclipse environment there is no need to syntactically distinguish fields in order to specially mark them as "fields" for yourself and generations to come.

查看更多
男人必须洒脱
3楼-- · 2020-08-21 05:34

Warning: Purely subjective answer below.

I think the best "reason" for not using this/self/me is brevity. If it's already a member variable/function then why redundantly add the prefix?

Personally I avoid the use of this/self/me unless it's necessary to disambiguate a particular expression for the compiler. Many people disagree with this but I haven't ever had it be a real sticking point in any group I've worked for.

查看更多
Luminary・发光体
4楼-- · 2020-08-21 05:37

'this.' in code always suggests to me that the coder has used intellisense (or other IDE equivalents) to do their heavy lifting.

I am certainly guilty of this, however I do, for purely vanity reasons, remove them afterwards.

The only other reasons I use them are to qualify an ambiguous variable (bad practice) or build an extension method

Qualifying a variable

string name; //should use something like _name or m_name

public void SetName(string name)
{
     this.name = name;
}
查看更多
叼着烟拽天下
5楼-- · 2020-08-21 05:41

It was asked before indeed, in the "variable in java" context:

Do you prefix your instance variable with ‘this’ in java ?

The main recurrent reason seems to be:

"it increases the visual noise you need to sift through to find the meaning of the code."

Readability, in other word... which I do not buy, I find this. very useful.

查看更多
6楼-- · 2020-08-21 05:43

In the end it's always a matter of personal choice. Personally, I use this coding convention:

public class Foo
{
  public string Bar
  {
    get
    {
      return this.bar;
    }
    /*set
    {
      this.bar = value;
    }*/
  }
  private readonly string bar;

  public Foo(string bar)
  {
    this.bar = bar;
  }
}

So for me "this" is actually necessary to keep the constructor readable.

Edit: the exact same example has been posted by "sinje" while I was writing the code above.

查看更多
SAY GOODBYE
7楼-- · 2020-08-21 05:43

It clarifies in some instances, like this example in c#:

public class SomeClass
{
    private string stringvar = "";

    public SomeClass(string stringvar)
    {
        this.stringvar = stringvar;
    }
}
查看更多
登录 后发表回答