What is the advantage of having this/self pointer mandatory explicit?

后端 未结 6 1101
死守一世寂寞
死守一世寂寞 2020-12-08 16:04

What is the advantage of having this/self/me pointer mandatory explicit?

According to OOP theory a method is supposed to operate mainly (only?) on m

相关标签:
6条回答
  • 2020-12-08 16:16

    You need it to pass the pointer/reference to the current object elsewhere or to protect against self-assignment in an assignment operator.

    0 讨论(0)
  • 2020-12-08 16:19

    In addition to member variables and method parameters you also have local variables. One of the most important things about the object is its internal state. Explicit member variable dereferencing makes it very clear where you are referencing that state and where you are modifying that state.

    For instance, if you have code like:

    someMethod(some, parameters) {
        ... a segment of code
        foo = 42;
        ... another segment of code
    }
    

    when quickly browsing through it, you have to have a mental model of the variables defined in the preceding segment to know if it's just a temporary variable or does it mutate the objects state. Whereas this.foo = 42 makes it obvious that the objects state is mutated. And if explicit dereferencing is exclusively used, you can be sure that the variable is temporary in the opposite case.

    Shorter, well factored methods make it a bit less important, but still, long term understandability trumps a little convenience while writing the code.

    0 讨论(0)
  • 2020-12-08 16:19

    I generally use this (in C++) only when I am writing the assignment operator or the copy constructor as it helps in clearly identifying the variables. Other place where I can think of using it is if your function parameter variable names are same as your member variable names or I want to kill my object using delete this.

    0 讨论(0)
  • 2020-12-08 16:19

    Eg would be where member names are same as those passed to method

    public void SetScreenTemplate(long screenTemplateID, string screenTemplateName, bool isDefault)
            {
                this.screenTemplateID = screenTemplateID;
                this.screenTemplateName = screenTemplateName;
                this.isDefault = isDefault;
            }
    
    0 讨论(0)
  • 2020-12-08 16:21

    If you are talking about "explicit self" in the sense of Python, here's an interesting discussion on the topic. Here's Guido responding to Bruce Eckel's article. The comments on Bruce's article are also enlightening (some of them, anyway).

    0 讨论(0)
  • 2020-12-08 16:33

    What if the arguments to a method have the same name as the member variables? Then you can use this.x = x for example. Where this.x is the member variable and x is the method argument. That's just one (trivial) example.

    0 讨论(0)
提交回复
热议问题