- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: ruby-best-practices/prevent-attr
Language: Ruby
Severity: Info
Category: Best Practices
The attr
method in Ruby is an older method that was commonly used before attr_accessor
, attr_reader
, and attr_writer
were introduced. It is now considered best practice to use these newer methods instead of attr
for better clarity and consistency in your code.
The attr
method can lead to confusion because it behaves differently depending on the number and type of arguments passed to it. If it is passed one argument, it behaves like attr_reader
, creating a getter method for an instance variable. If it is passed two arguments, with the second argument being true
, it behaves like attr_accessor
, creating both a getter and a setter method. This can lead to unexpected behavior if not used carefully.
To adhere to this rule and avoid confusion, always use attr_accessor
to create both getter and setter methods, attr_reader
to create only getter methods, and attr_writer
to create only setter methods. This will make your code more readable and maintainable. Avoid using attr
altogether. For example, instead of writing attr :something, true
, write attr_accessor :something
. Instead of attr :one, :two, :three
, write attr_reader :one, :two, :three
.
class Something
attr :something, true
attr :one, :two, :three
end
class Something
attr_accessor :something
attr_reader :one, :two, :three
end
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products