Avoid hash optional paramters

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: ruby-best-practices/no-optional-hash-params

Language: Ruby

Severity: Notice

Category: Best Practices

Description

The rule “Avoid hash optional parameters” is a guideline that encourages developers to explicitly declare parameters instead of using a hash for optional parameters. This is because using a hash for optional parameters can make the code harder to understand and maintain. It can also lead to unexpected behavior if a developer accidentally includes a key in the hash that the method does not expect.

This rule is important because it promotes code readability and maintainability. It also helps prevent potential bugs that may occur due to unexpected keys in the optional hash. By explicitly declaring each parameter, developers can easily see what parameters a method expects, making the code easier to read and understand.

To adhere to this rule, instead of using a hash for optional parameters, explicitly declare each parameter in the method definition. For example, instead of using options = {} in the method definition, declare each parameter like name, email, age. This way, anyone reading the code can easily understand what parameters the method expects and in what order.

Non-Compliant Code Examples

def create_person(options = {})
  person = Person.new(options)
  person.save
  person
end

Compliant Code Examples

def create_person(name, email, age)
  person = Person.new(name: name, email: email, age: age)
  person.save
  person
end
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis