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
- best practices
- Ruby
- balance
- brevity
- public vs. private interface
- good point
- accessors
- go through accessor instead of using instance variable directly
- JavaScript
- good explanation
- I agree
- extracting small reusable snippets of code
- programming languages: external objects have direct access to instance variables
- good policy/practice/procedure
- JavaScript: private instance accessors
- annotation meta: may need new tag
- reusability
- avoid duplication
- programming: access modifiers (public/private)
- languages: differences
- metaprogramming
- Ruby: instance variables
- self-enforced
- safety (programming)
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}!`); } }
-