Daily Refactor #39: Substitute Algorithm for Checking the Settings

Since I’m planning to release an update to my StuffToDo plugin next, I decided it could use a week of refactoring in order to clean it up.

The Refactoring

Today I did the second part of the refactoring from yesterday to clean up the StuffToDo plugin’s #using_projects_as_items? and #using_issues_as_items? methods. This time I used “substitute algorithm” to refactor the inner logic.

Before

1
2
3
4
5
6
7
8
9
10
# app/models/stuff_to_do.rb
class StuffToDo < ActiveRecord::Base
  def self.using_projects_as_items?
    use_setting == 'All' || use_setting  == 'Only Projects'
  end
 
  def self.using_issues_as_items?
    use_setting == 'All' || use_setting  == 'Only Issues'
  end
end

After

1
2
3
4
5
6
7
8
9
class StuffToDo < ActiveRecord::Base
  def self.using_projects_as_items?
    ['All', 'Only Projects'].include?(use_setting)
  end
 
  def self.using_issues_as_items?
    ['All', 'Only Issues'].include?(use_setting)
  end
end

Review

This was a simple refactoring but it really made the intent of the methods clear. Removing the extra method calls and using an Array of valid values will make it easier to modify later. This refactoring also made flay happy enough to report that the duplication has been completely removed.

Reference commit