# 修正前のコード
class TestClass
attr_accessor :name, :str
def initialize(name)
@name = name
@str = ""
end
def make_hello
@str = "Hello, World. I am #{@name}.\n"
end
def hello
puts @str
end
# インスタンス変数を使用していないメソッドがたくさんある
end
# 修正後のコード
class TestClass
attr_accessor :name
def initialize(name)
@name = name
end
def make_hello
@@str = "Hello, World. I am #{@name}.\n"
end
def hello
puts @@str
end
# その他メソッドは変数strが見えない
end
# テスト2−2の一部抜粋
#素数判定関数の生成
def prime?(num)
if num < 2
return false
else
2.upto(Math.sqrt(num)) do | i |
if num % i == 0
return false
end
end
return true
end
end
読みやすいコードである必要性
読みやすいコードにする目的は、チームでの開発を円滑にすることにある。読みやすい、また意味がわかりやすいコードであることで、他者(自分も含めて)がコードの理解や修正を行いやすくなる。
読みやすいコードとは
変数
インデントの活用
コメントの活用
制御フロー
if/else ブロックの並び順 基本的には条件は否定形よりも肯定形を使い、また、単純な条件や関心の引く条件を先に書くことでわかりやすい条件式を書くことができる(また、計算量踏まえて、先に書く条件を選択することもある)。
関数から早く返す 処理の対象外とする条件を先頭に集め、早めにreturnで抜けることでネストを減らし、エラー時の処理と通常時の処理をわかりやすくする。下記の例の条件文①では、false(エラー時)となる条件のnum1 == 0、num2 == 0の時にはfalseを返すように先頭行で指定している。
テストと読みやすさ
その他