12 Matching Annotations
- Jun 2021
-
developer.mozilla.org developer.mozilla.org
-
The encapsulation is enforced by the language. It is a syntax error to refer to # names from out of scope.
-
-
github.com github.com
-
-
github.com github.com
-
stackoverflow.com stackoverflow.com
-
When defining accessors in Ruby, there can be a tension between brevity (which we all love) and best practice.
-
a principle I use is: If you have an accessor, use the accessor rather than the raw variable or mechanism it's hiding. The raw variable is the implementation, the accessor is the interface. Should I ignore the interface because I'm internal to the instance? I wouldn't if it was an attr_accessor.
-
in languages (like JavaScript and Java) where external objects do have direct access to instance vars
-
But suddenly I'm using a raw instance variable, which makes me twitch. I mean, if I needed to process has_sauce before setting at a future date, I'd potentially need to do a lot more refactoring than just overriding the accessor.
-
One of the consequences (although arguably not the primary motivation) of DRY is that you tend to end up with chunks of complex code expressed once, with simpler code referencing it throughout the codebase. I can't speak for anyone else, but I consider it a win if I can reduce repetition and tuck it away in some framework or initialisation code. Having a single accessor definition for a commonly used accessor makes me happy - and the new Object class code can be tested to hell and back. The upshot is more beautiful, readable code.
new tag?:
- extract reusable functions to reduce duplication / allow elegant patterns elsewhere
-
class << Object def private_accessor(*names) names.each do |name| attr_accessor name private "#{name}=" end end end
Tags
- balance
- JavaScript
- good policy/practice/procedure
- brevity
- reusability
- programming: access modifiers (public/private)
- good point
- self-enforced
- metaprogramming
- public vs. private interface
- good explanation
- Ruby: instance variables
- JavaScript: private instance accessors
- best practices
- I agree
- go through accessor instead of using instance variable directly
- languages: differences
- annotation meta: may need new tag
- extracting small reusable snippets of code
- safety (programming)
- accessors
- Ruby
- programming languages: external objects have direct access to instance variables
- avoid duplication
Annotators
URL
-
-
stackoverflow.com stackoverflow.com
-
Note: there’s no way to define private methods, getters and setters. but a proposal is there https://github.com/tc39/proposal-private-methods
-
-
babeljs.io babeljs.io
-
Private instance accessors (getters and setters)
-
class Person { #firstname = "Babel"; #lastname = "JS"; get #name() { return this.#firstname + " " + this.#lastname; } sayHi() { alert(`Hi, ${this.#name}!`); } }
-