▼例1▼
Public Function 割算(ByVal x As Integer, ByVal y As Integer) As Integer
Return CInt(x / y)
End Function
▲例1▲
これだけだと, y=0の時,死ぬので,失格です。
▼例2▼
Public Function 割算(ByVal x As Integer, ByVal y As Integer) As Integer
if y=0 then
Throw New ApplicationException("除数が0です")
end if
Return CInt(x / y)
End Function
▲例2▲
これでOKでしょ. (除数0以外の例外はややこしくなるのでスルー)
呼ぶ側が
dim a as Integer =45
dim b as Integer =0
dim ans as integer = 割算(a,b)
でなく
dim a as Integer =45
dim b as Integer =0
if 割算妥当性check(a,b) then
dim ans as integer = 割算(a,b)
' ansを使った処理…
end if
としてあり,割算妥当性checkが
▼例3▼
Public Function 割算妥当性check(ByVal x As Integer, ByVal y As Integer) As boolean
if y=0 then
return false
end if
Return true
End Function
▲例3▲
としてある場合の 割算はどう記述すべきか
▼例4▼
Public Function 割算(ByVal x As Integer, ByVal y As Integer) As Integer
Return CInt(x / y)
End Function
▲例4▲
これで良いと思いますが、単体でみると潜在バグを孕んでいるコードに見えてしまいます。
同一ソース上で割算妥当性check()が見えるので, 理解を得られますが, コードが見えない場合、不安になりすま。
このように,事前にエラー要因が弾かれてる場足, メインメソッド(割算()) での y=0の対処は不要ですよね(?)
しかし、コピペで割算() の部分だけ他に流用されて潜在バグだと騒がれて嫌な目をしたくないので,冗長だがエラーチェックをつけたりすることもあります。
結局ケースバイケースでしょうが。どうされています?