LoginSignup
13

More than 5 years have passed since last update.

for文を回すときのi,jの名前をひと工夫すると、間違いが起きにくくなる

Last updated at Posted at 2013-02-25

リーダブルコード ―より良いコードを書くためのシンプルで実践的なテクニックがとても良い感じなのでシェア。例えば以下のコードは配列から行列を作るコードだが、afterのようにfor文を回すときのi,jの名前をひと工夫すると、間違いが起きにくいコードに生まれ変わる。

before
  _putShuffleMatrix: ->
    a = []
    a = @_putShuffleArray()
    b = []
    for i in [0...@height]
      b[i] = []
      for j in [0...@width]
        b[i][j] = a[i * @width + j]
    return b
after
  putShuffleMatrix_: ->
    shuffleArray = []
    shuffleArray = @putShuffleArray_()
    shuffleMatrix = []
    for height_i in [0...@height]
      shuffleMatrix[height_i] = []
      for width_j in [0...@width]
        shuffleMatrix[height_i][width_j] =
        shuffleArray[(height_i * @width) + width_j]
    return shuffleMatrix

ブログやってます:PAPA-tronix !

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13