Rubberduck icon indicating copy to clipboard operation
Rubberduck copied to clipboard

Inspection for optional argument default values that are expressions

Open ThunderFrame opened this issue 8 years ago • 1 comments

The default value for an optional argument must be a "constant expression", but that constant expression can be anything that results in a constant expression, including operators, and certain built-in functions.

The signature is not the place to be performing arithmetic or conversions. A better design would involve declaring a constant scoped to the module, and having the optional argument default to that constant. But constants can't use any functions I hear you protest. That's true, in those cases, you might have to get funky with an Enum?

Sub bar(Optional x As Long = Int(1.5 + 12) / 16, Optional y As Double = 42 + 0.5)
  Debug.Print x, y
End Sub

Becomes:

Enum MEANING_OF_LIFE
  Value = Int(1.5 + 675) / 16 'Implicit narrowing cast from 42.25 to 42
End Enum

Const ACCURATE_MEANING_OF_LIFE As Double = 42 + 0.25

Sub bar(Optional x As Long = MEANING_OF_LIFE.Value, Optional y As Double = ACCURATE_MEANING_OF_LIFE)
  Debug.Print x, y
End Sub

You might make the argument that bitwise arithmetic is permissible in the signature:

Sub ShowMessageBox(Optional style As VBA.VbMsgBoxStyle = VbMsgBoxStyle.vbInformation And VbMsgBoxStyle.vbOKOnly)
  Beep
End Sub

ThunderFrame avatar Jun 07 '17 02:06 ThunderFrame