advice on enumerations in classes and enum string value

skinny monkey
04-11-2005, 12:54 PM
I was looking for some general advice about using enumerations in classes.

Say i have a class, clsUser, with the following enum:


public enum enuGender
Male = 0
Female = 1
end enum


To use these, i declare a private integer to hold the selected enum index. Is this right?


Private intSelectedGender as integer

Public property Get Gender() as enuGender
Gender = intSelectedGender
end property

Public Property Let Gender(byval sex as enuGender)
intSelectedGender = sex
end property


At this point i want to ask my second question - is it acceptable to store enum integer values in a database? For instance, in my db table of Users, should i store 0 / 1 under the gender field, or translate this integer value into a string representation of "Male" / "Female" ?

This ties in with my third question - should i get string values for the selected enum value? At the moment, i have not, and wherever i access my User class, the calling code is littered with:


select case objUser.Gender
case 0
text1.text = "Male"
case 1
text1.text = "Female"
end select


which seems quite redundant and would be a pain to change in the future. I thought of a public class property that would get the string value of the selected enum index, something like:


Public Property Get GenderString() as string
select case intSelectedGender
case 0:
GenderString = "Male"
case 1:
GenderString = "Female"
end select
end propety


which i could access like:

text1.text = objUser.GenderString


But then this bloats the class interface. Whats the opinion of this approach?

(by the way i'm using vb6)

herilane
04-11-2005, 03:00 PM
Yes, that's how you would normally do it. You might want to make that a Long instead of an Integer (since Enums evaluate to Longs according to MSDN).
I'm not a database expert, but it looks fine to me. Storing integers appears more robust than storing strings. As long as you don't change your enum values of course.
I would definitely use a GenderString property instead of letting the form decide what 0 and 1 mean. That way, if you ever want to change it (translate it to Swahili or whatever) then you only need to change the strings in one place, and you reduce the risk of bugs as well. As long as the property names are systematic and well-chosen, I'd rather have a bloated interface than an all-knowing form.

skinny monkey
04-11-2005, 07:36 PM
Thanks for your advice.

;)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum