labyrinth
labyrinth

Reputation: 13956

What is good design and style practice regarding use of attr and visibility (e.g. private, public)?

So I understand that the attr syntax sugar in ruby translates into just defining instance variables and methods for writing/reading them.

What I'm wanting to know is, what are the best practices for design if you are trying to keep your class public interfaces minimal? Should you avoid attr_accessor like unless very clearly public? How do attr_writer and attr_reader fit into public/private visibility?

If it makes sense, say, to use attr_reader for private fields that are often read, should you use attr_reader liberally and not even define the fields explicitly?

Upvotes: 0

Views: 72

Answers (1)

sawa
sawa

Reputation: 168199

The purpose of attr methods is to let access to instance variables possible from outside of an instance. Hence, (over)use of such methods is already against object oriented programming. If you only need to access them from an instance, which is preferable from the point of view of object oriented design, you can directly refer to the instance variables:

@foo = 3
@foo # => 3

You should not need attr methods.

Upvotes: 1

Related Questions