[英]How can I make this method more concise?
在Rails項目上運行reek時我收到警告:
[36]:ArborReloaded :: UserStoryService#destroy_stories有大約8個語句(TooManyStatements)
這是方法:
def destroy_stories(project_id, user_stories)
errors = []
@project = Project.find(project_id)
user_stories.each do |current_user_story_id|
unless @project.user_stories.find(current_user_story_id).destroy
errors.push("Error destroying user_story: #{current_user_story_id}")
end
end
if errors.compact.length == 0
@common_response.success = true
else
@common_response.success = false
@common_response.errors = errors
end
@common_response
end
如何最小化這種方法?
首先,我發現類和方法大小對於查找可能需要重構的代碼很有用,但有時您確實需要一個長類或方法。 並且始終有一種方法可以縮短您的代碼以克服這些限制,但這可能會降低您的可讀性。 所以我在使用靜態分析工具時禁用了那種類型的檢查。
此外,我不清楚為什么您在刪除故事時會出現錯誤,或者從包含ID的錯誤消息中獲益,而不會發生錯誤。
也就是說,我會像這樣編寫這種方法,以減少顯式的本地狀態並更好地區分問題:
def destroy_stories(project_id, story_ids)
project = Project.find(project_id) # I don't see a need for an instance variable
errors = story_ids.
select { |story_id| !project.user_stories.find(story_id).destroy }.
map { |story_id| "Error destroying user_story: #{story_id}" }
respond errors
end
# Lots of services probably need to do this, so it can go in a superclass.
# Even better, move it to @common_response's class.
def respond(errors)
# It would be best to move this behavior to @common_response.
@common_response.success = errors.any?
# Hopefully this works even when errors == []. If not, fix your framework.
@common_response.errors = errors
@common_response
end
您可以看到在您的框架中如何小心處理可以在組件中節省大量噪音。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.