There is nothing wrong with enums, they are quite common even in the .NET Framework itself. They do have some minor flaws but they should only appear when you're not using them as intended.
Behind the scenes, an enum value is just an integer. The enum simply helps you avoid 'magic numbers' in your code by 'substituting' the integer with a named value.
For example, a method might return an error code if something went wrong. You could handle that like this:
These values (especially 391 and -593) don't make sense to anyone except if you know what they mean.Code:Dim error As Integer = Me.RunSomeMethod() If error = 0 Then MessageBox.Show("Success!") ElseIf error = 391 Then MessageBox.Show("Connection failed") ElseIf error = -593 Then MessageBox.Show("Timeout") End If
If you use an enum you can replace these values by a proper name:
Code:Public Enum ErrorCode Success = 0 ConnectionFailed = 391 Timeout = -593 End Enum Dim error As ErrorCode = Me.RunSomeMethod() If error = ErrorCode.Success Then MessageBox.Show("Success!") ElseIf error = ErrorCode.ConnectionFailed Then MessageBox.Show("Connection failed") ElseIf error = ErrorCode.Timeout Then MessageBox.Show("Timeout") End If
What Evil Giraffe shows you (the object enumeration pattern) is like an extension to the regular enum. An enum 'maps' a name to an integer value. EG's code 'maps' a name to an actual object, which can have methods and properties specific to that object. The usage in the end is similar. If you created an ErrorCode class as in the object enumeration pattern you could do something like this:
Respond is now a method on the ErrorCode class, actually on one specific implementation of the abstract ErrorCode class (either SuccessErrorCode, ConnectionFailedErrorCode or TimeoutErrorCode, for example). Each of these implementations has their own implementation for the Respond method, so each could show a different message.Code:Dim error As ErrorCode = Me.RunSomeMethod() If error = ErrorCode.Timeout Then MessageBox.Show("Timeout") Else error.Respond() End If
In short, an enum is a perfectly fine choice for your purpose. Once you see that you might want to put some actual functionality in your enum values (it doesn't seem that way as they are constants you say), then you can take a look at the object enumeration pattern.




Reply With Quote
