5 ms·
Is there a reason for not using 'this'? I assume the risk is that you might have a scope where both this->foo and foo are valid and it's unclear which is which.
by joshvm 8y ago
Is there a reason for not using 'this'? I assume the risk is that you might have a scope where both this->foo and foo are valid and it's unclear which is which. You have no ambiguitiy with this->foo_, and foo (and if you forget 'this', foo_ is still clear).
- jcelerier 8y agosix characters to type vs 1 ?
- joshvm 8y agoYou can argue that either way. Seeing 'this' unambiguously implies instance variable. Otherwise you have to spot the underscore and be aware of the conventions in the codebase. A good IDE should highlight class variables vs locals, though. On the other hand code can get really messy with boilerplate like this everywhere, and I personally agree with you. Although I believe Google also promotes human-readable variables over less typing.
- tokyodude 8y agoI actually think implicit "this" is a language wart. I think C++, C#, Java, Swift, etc.. would all be better languages if they required `this`. As it is, nearly every one of them ends up needing a per team naming convention to help make the code readable. int area(int width) { return width * height; } What is "height". Is it a global variable? variable in some outer scope? A member/property of the current object? Absolutely no idea.
- amalcon 8y agoRules like this are usually less about risk, and more about conveying information. If I see a variable ending in "_", I immediately know to look for its definition in the class rather than the local scope.
- nolok 8y agoI assume it's because if a dev forgets a this somewhere as a caller/accessor, you now have two problems; whereas if they forget a _, it doesn't compile.
- pjc50 8y agoIt's unidiomatic? > scope where both this->foo and foo are valid and it's unclear which is which Ideally you'd turn on the compiler option to warn about scope hiding.
- joshvm 8y agoMaybe, though it's a common thing I've seen in setter functions or constructors: Eg void set_foo(int foo) {this->foo = foo;}