If/then/else is one of the first things a new programmer learns. But, like any tool, it can be overused. Too much conditional logic makes your methods hard to understand and reason about. What if we started thinking about our code differently? What if we started telling our code what to do instead of asking it what it can do? This talk will go through a real refactoring from a method with more than 30 if/then/else statements to a solution with no conditional logic whatsoever.
Which version of the code do you find more clear and/or preferable?
I recently tried to retrofit STI on a database table that had already existed for a while. Here's a basic outline of the scenario.
- I had a class 'Code' and a database table 'codes'.
- 'Code' had an attribute 'units', which could be either '$' or '%'
- I wanted the STI classes to be Code::Dollar or Code::Percent
I successfully implemented this with the following:
class Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var anagram = function(word) { | |
return new Anagram(word); | |
}; | |
function Anagram(word) { | |
this.matches = matches; | |
function matches() { | |
possible_anagrams = retrieveAnagrams(arguments); | |
return possible_anagrams.filter(function(anagram) { |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Calculator | |
attr_reader :string_to_calculate | |
def initialize(string_to_calculate, options = {}) | |
@string_to_calculate = string_to_calculate | |
@delimiter = options[:delimiter] | |
end | |
def add | |
raise ArgumentError, error_message unless negatives.empty? |