Skip to content

Instantly share code, notes, and snippets.

@joseph-ravenwolfe
Last active June 16, 2016 23:36
Show Gist options
  • Save joseph-ravenwolfe/3f1a8661a7bd76cf307438228d3423e9 to your computer and use it in GitHub Desktop.
Save joseph-ravenwolfe/3f1a8661a7bd76cf307438228d3423e9 to your computer and use it in GitHub Desktop.

Pattern 1

# Bad
class Person
  def be_polite(big_favor)
    if big_favor
      'Thank you very much'
    else
      'Thank you'
    end
  end
end

Person.new.be_polite(true)
Person.new.be_polite(false)


# Good
class Person
  def thanks
    'Thank you'
  end

  def much_thanks
    'Thank you very much'
  end
end

Person.new.much_thanks
Person.new.thanks

Pattern 2

# Bad
class Bird
  attr_accessor :nailed?, :type

  BASE_SPEED = 10
  LOAD_FACTOR = 3

  def initialize(nailed=false, type=nil)
    self.nailed? = nailed
    self.type = type
  end

  def speed
    case type
    when :european
      BASE_SPEED
    when :african
      BASE_SPEED - LOAD_FACTOR
    when :norwegian
      nailed? ? 0 : BASE_SPEED
    else
      0
    end
  end
end


# Good
class Bird
  BASE_SPEED = 10
  LOAD_FACTOR = 3

  def speed
    0
  end
end

class EuropeanBird < Bird
  def speed
    BASE_SPEED
  end
end

class AfricanBird < Bird
  def speed
    BASE_SPEED - LOAD_FACTOR
  end
end

class NorwegianBird < Bird
  attr_accessor :nailed?

  def initialize(nailed)
    self.nailed? = nailed
    super
  end

  def speed
    nailed? ? 0 : BASE_SPEED
  end
end

Pattern 3

# Bad
def sum(numbers)
  return 0 unless numbers
  numbers.reduce(:+)
end

# Good
def sum(numbers=[])
  numbers.reduce(:+)
end

Pattern 4

# Bad
def horrible(foo, bar, baz)
  if foo
    if bar
      true
    end
  end
  if baz
    true
  else
    false
  end
end

# Good
def horrible(foo, bar, baz)
  foo && bar || baz
end

Pattern 5

# Bad
class Repository
  def record_name(id)
    DB.find(id).name
  end
end

class Finder
  def display_record(repository)
    name = repository.record_name(123)
    return "No name" unless name
    name
  end
end

# Good
class Repository
  def record_name(id, default_name)
    result = DB.find(id)
    return result.name if result
    default_name
  end
end

class Finder
  def display_record(repository)
    repository.record_name(123, 'No name')
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment