12 Matching Annotations
  1. Jun 2021
    1. When defining accessors in Ruby, there can be a tension between brevity (which we all love) and best practice.
    2. 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.
    3. in languages (like JavaScript and Java) where external objects do have direct access to instance vars
    4. 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.
    5. 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
    6. class << Object def private_accessor(*names) names.each do |name| attr_accessor name private "#{name}=" end end end