아름다운 Ruby 코드를 위한 리팩토링 체크리스트


리팩토링의 중요성을 과소평가해서는 안 됩니다. Ruby를 처음 사용하는 경우 Ruby의 편리한 구문을 사용하는 방법을 모른 채 예상보다 더 길고 복잡한 코드를 작성하고 있을 수 있습니다. 코딩 부트캠프에서 기본적인 Ruby를 배운 이후로 숙련된 개발자의 코드에서 배우려고 노력했고 내 코드가 훨씬 장황하고 혼란스럽다는 것을 깨달았습니다. 이 기사에서는 Ruby 코드를 더 읽기 쉽고 저렴하며 변경하기 쉽게 만드는 몇 가지 기술을 소개합니다.

조건식


1. 사용하지 않는 한



선호도에 따라 다를 수 있습니다.

# Bad
user.destroy if !user.active?

# Good
user.destroy unless user.active?



2. 삼항 연산자 ?:




# Bad
if score > 8
  result = "Pass"
else
  result = "Fail"
end

# Good
result = score > 8 ? "Pass" : "Fail" 



3. == true , == false 및 == nil을 피하십시오.




# Bad
if foo == true
  # something
end

# Good
if foo
  # something
end



# Bad
if bar == false
  # something
end

# Good
if !bar
  # something
end
# or
unless bar
  # something
end



# Bad
if baz == nil
  # something
end

# Good
if !baz
  # something
end
# or
unless baz
  # something
end


또는 값이 구체적으로 nil이고 다른 잘못된 값이 아닌지 확인해야 하는 경우 다음이 더 나은 옵션일 수 있습니다.

# Good
if baz.nil?
  # something
end



4. 한 줄 if 문




# Bad
if num > 5
  puts "#{num} is greater than 5"
end

# Good
puts "#{num} is greater than 5" if num > 5



5. 안전한 항해사 &. (루비 2.3.0 이후)



안전 탐색 연산자&.는 수신자가 nil일 때 메소드 호출 건너뛰기를 허용합니다.

아래 예에서 book.author 또는 book.author.namenil를 반환하는 경우 NoMethodError 예외를 방지하려면 확인해야 합니다.

# Bad
if book.author
  if book.author.name
    puts "#{book.title} was written by #{book.author.name}"
  end
end


안전한 내비게이션 연산자를 사용하면 더 적은 수의 코드로 이를 달성할 수 있습니다.

# Good
if book.author&.name
  puts "#{book.title} was written by #{book.author.name}"
end



6. 조건부 초기화에 ||= 사용




# Bad
book = Book.new if book.nil?

# Good
book ||= Book.new



정렬



7. 배열을 만들 때 %w() 또는 %i()를 사용하십시오( 백분율 문자열 ).



퍼센트 문자열을 사용하는 것이 따옴표나 콜론을 잊어버리거나 오류를 만드는 것을 방지할 수 있기 때문에 더 나은 방법이라고 말하고 싶습니다.

# Bad
genres = [ "fantasy", "adventure", "mystery", "romance" ]

# Good
# String
genres = %w(fantasy adventure mystery romance)
# =>[ "fantasy", "adventure", "mystery", "romance" ]

# Symbol
genres = %i(fantasy adventure mystery romance)
# =>[ :fantasy, :adventure, :mystery, :romance ]



8. 배열을 반복할 때 &(앰퍼샌드) 연산자 사용




# Bad
titles = books.map { |book| book.title }

# Good
titles = books.map(&:title)


자세한 내용은 반복 및 & 연산자에 대한 내 블로그 게시물을 참조하십시오.


9. .last 메소드를 사용하여 배열의 마지막 요소를 가져옵니다.




genres = [ :fantasy, :adventure, :mystery, :romance ]

# Bad
genres[genres.length - 1] # => :romance

# Good
genres.last # => :romance



10. 디스트럭처링 할당



구조 분해는 배열과 같은 객체에 저장된 데이터에서 여러 값을 추출하는 편리한 방법입니다.

quotient, remainder = 20.divmod(3) # => [6, 2]
quotient # => 6 
remainder # => 2 



기타



11. Heredoc(여기 문서)



큰 텍스트 블록을 작성하는 경우 heredoc을 사용하면 더 깔끔하고 읽기 쉽게 만들 수 있습니다.

# Bad
text = "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam,\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."

# Good
text = <<-TEXT
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
TEXT



이 기사가 도움이 되었기를 바라며 추가할 제안이 있으면 댓글을 남겨주세요!

좋은 웹페이지 즐겨찾기