Logo

Why use Ruby's attr_accessor, attr_reader and attr_writer?

Using attr_accessor, attr_reader, and attr_writer in Ruby is a concise way to define getter and setter methods for your class attributes:

  1. attr_reader :attribute
    Creates a getter method that allows you to read the value of @attribute from outside the class.

    class Person attr_reader :name # Creates def name; @name; end def initialize(name) @name = name end end
  2. attr_writer :attribute
    Creates a setter method that allows you to write (assign) a value to @attribute.

    class Person attr_writer :name # Creates def name=(value); @name = value; end def initialize(name) @name = name end end
  3. attr_accessor :attribute
    Creates both a getter and a setter, allowing you to read and write the value of @attribute.

    class Person attr_accessor :name # getter + setter def initialize(name) @name = name end end

Why Use These Methods?

  1. Encapsulation:

    • They hide your instance variables from direct external manipulation, providing a clear interface for how attributes should be accessed or modified.
  2. Concise Code:

    • Instead of writing separate def name; end and def name=(new_name); end methods, you can declare attr_accessor :name in one line.
  3. Read-Only and Write-Only Attributes:

    • Use attr_reader to restrict access to “read-only” if other parts of your code should not modify that value.
    • Use attr_writer for “write-only” scenarios where code outside your class shouldn’t read the internal state.
  4. Clarity and Intent:

    • attr_reader :status explicitly communicates that status is an attribute that can be read publicly, but not set externally.

Pitfalls and Best Practices

  1. Don’t Overuse attr_accessor

    • Exposing all internal state with attr_accessor can break encapsulation and lead to tight coupling. Only provide getters and setters when truly necessary.
  2. Add Validations or Hooks If Needed

    • If you need to validate or transform data on assignment, you may prefer defining a custom writer method rather than a simple attr_writer.
  3. Immutable Objects

    • Some Rubyists prefer immutable objects (only readers) once set in the initializer. In such cases, only attr_reader is used and the values can’t be changed later.

If you want to build a deeper understanding of Ruby (and software development in general), here are two recommended courses from DesignGurus.io:

To get personalized advice from ex-FAANG engineers, check out the Coding Mock Interview or System Design Mock Interview services.

CONTRIBUTOR
TechGrind