6
\$\begingroup\$

I have two implementations of a function that prints out a basic board for Tic-Tac-Toe.

Which of these should I include and why?

def display_board(board)
  for i in 0...9
    print " #{ board[i] }"
    if (i+1)%3 != 0
      print " |"
    elsif i != 9
       print " \n#{'-'*11}\n"
    end
  end
end

def display_board(board)
  puts " #{board[0]} | #{board[1]} | #{board[2]} "
  puts "-----------"
  puts " #{board[3]} | #{board[4]} | #{board[5]} "
  puts "-----------"
  puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

Surely version two.

  • It makes no use of control structures such as for or if, it has very low Kolmogorov complexity because of that, and it is good, as it is directly related to difficulty in understanding.

  • It lets you see in a single glance what the output will look like.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Without even understanding the code, I have a visceral attraction to the 2nd version and a repulsion to the first, a reaction that occurs in well under half a second. It's interesting how often these gut reactions to the visual appearance of code turn out to be a correct assessment of readability and other more rigorous complexity metrics. \$\endgroup\$
    – Jonah
    Oct 20, 2015 at 20:29
  • 2
    \$\begingroup\$ @Jonah I also had that sensation in less than a second, but half a second after I though "What about extensibility?" promptly followed by "Tic-Tac-Tac is only ever 3x3 so extensibility is not a problem". \$\endgroup\$
    – Caridorc
    Oct 20, 2015 at 20:51
  • 1
    \$\begingroup\$ Yeah, I think it's great mini-lesson in the costs of abstraction, and a reminder to think about the likely changes in your domain, and know when making something brittle but simple is the right choice. \$\endgroup\$
    – Jonah
    Oct 20, 2015 at 20:59
2
\$\begingroup\$

If I had to pick, I'd take the second version. Not that the first approach is bad, it just needs a refactor. I'd write:

def display_board(board)
  puts board.each_slice(3).map { |row| row.join(" | ") }.join("\n" + "-"*11 + "\n")
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.