3 ms·
"this" is not just superfluous -- if you use it, you lose the referential transparency of the call. If you don't use "this" you can change where your call is im
by thelazydogsback 6y ago
"this" is not just superfluous -- if you use it, you lose the referential transparency of the call. If you don't use "this" you can change where your call is implemented to any of these places without refactoring all the calls:
- In current class
- In a base class
- A static method in the current class
- A "static import"ed helper method from outside the class
In the past I'd say you could use it to be self-documenting, but these days you have semantic colorizing, tooltips, etc., for this sort of discovery if you want it.
- ddek 6y agoNo? If your call is implemented in the current class, the 'this' is implicit. If the call is implemented in a base class, and not overriden, the base class method is still available through the 'this' keyword. If you do override the base method, you must explicitly do so. Why you would want to call the base in a class which overrides it, I don't know. Static methods in the same class are impossible. You can't have two methods with the same signature, static or otherwise. Extension methods are different, but there is clear precedence. The instance method is used before the extension. 'this.ExtensionMethod()' is still valid, so you aren't getting any of this referential transparency. In any case, the only use case for 'this' is to call extension methods from within a class the extension is defined for. It certainly does not give any referential transparency.
- thelazydogsback 6y agoI'm not sure I'm following your objections at all - if this is implicit, then you don't need it, correct? > Static methods in the same class are impossible. You can't have two methods with the same signature, static or otherwise. I never said anything about having both at once -- I was talking about refactoring - changing the location of where the fn was defined - from a method to a static. (As one does if it turns out you're not using any object state.) Of course, some languages let you call static's on the same class with 'this' and some can only reference instance methods.