Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant inside class

I've tried to create a vb scripts class with a constant and got 800A03EA error. It's it a VBS bug? Isn't it an OOP fundamental rule?

Class customer
   ' comment it const and its works
   const MAX_LEN=70

   Private Name

   Private Sub Class_Initialize
      Name = ""
   End Sub

   ' name property.
   Public Property Get getName
      getName = Name
   End Property

   Public Property Let letName(p_name)
      Name = p_name
   End Property
end class
like image 924
gwarah Avatar asked Jan 10 '14 18:01

gwarah


1 Answers

The documentation lists all statements that are allowed in the context of classes. Const isn't among them, so it's not supported. You can work around the issue by using private member variables that you initialize during instantiation (i.e. in Class_Initialize):

Class customer
  Private MAX_LEN
  Private Name

  Private Sub Class_Initialize
    MAX_LEN = 70
    Name = ""
  End Sub

  ...
End Class

If instances of the class should expose this value, you could implement it as a read-only property:

Class customer
  Private MAX_LEN

  Private Sub Class_Initialize
    MAX_LEN = 70
  End Sub

  'read-only property, so no "Property Let/Set"
  Public Property Get MaxLength
    MaxLength = MAX_LEN
  End Property

  ...
End Class

However, as Ekkehard.Horner pointed out correctly, the value could still be changed by object-internal code. If immutability is the primary requirment for this value you should implement it as a global constant.

like image 95
Ansgar Wiechers Avatar answered Oct 21 '22 17:10

Ansgar Wiechers