3 simple rules to improve your code

1. Small classes

  • Forces to think about architecture
  • You have to define class responsibility
  • Complex file vs Simple files
  • Do not fear adding files/classes

2. Small methods

  • Easier to understand
  • Name the things
  • From top to bottom
class Words
  def initialize(phrase)
    @words = phrase.split(" ")
  end

  def num_of_palindromes
    @words.reduce(0) do |sum, word|
      if word == word.reverse 
        sum += 1
      else
        sum
      end
    end
  end
end
class Words
  def initialize(phrase)
    @words = find_words(phrase)
  end

  def num_of_palindromes
    select_palindromes(@words).count
  end

  private

  def find_words(phrase)
    phrase.split(" ")
  end

  def select_palindromes(words)
    words.select { |word| palindrome?(word) }
  end

  def palindrome?(word)
    word == word.reverse
  end
end

3. Do not use if

  • If are source of evil and sometimes bugs
  • You will learn patterns in theory
  • And in practice

https://sourcemaking.com/refactoring/simplifying-conditional-expressions

Questions?

3 simple rules to improve your code

By Jan Dudulski

3 simple rules to improve your code

  • 148