Public Mutable Field (ARCH6186)
Ce contenu n’est pas encore disponible dans votre langue.
Key ruby.quality.public-mutable-attr · Severity warning · Category quality
Directly exposed mutable fields (attr_accessor) bypass validation and invariants; the object’s internal state can be corrupted from anywhere.
Incorrect
Section titled “Incorrect”class Account attr_accessor :balance
def initialize @balance = 0 endendCorrect
Section titled “Correct”class Account attr_reader :balance
def initialize @balance = 0 end
def deposit(amount) raise ArgumentError if amount.negative? @balance += amount endendDrop the writer and route state changes through explicit methods that enforce validation.