Let me use medical doctors to explain my question. Now doctors have different fields of specialization, like Neurologist=0,Oncologist=1,Cardiologist=2,Gynecologist=3 etc. Let’s say I have a method that takes one of these specialities as an integer and uses it as a parameter to a stored procedure in a database:
DisplaySkills(int speciality)
{
//create a connection to a database, refer to a stored procedure in the database;
//send "speciality" as an argument to that stored procedure
}
Now, here I’m sort of in a dilemma as to whether I should have those specialities inside an enum or declare them seperately. From the first sight it feels like I should go with enums because it’s just the case where “one thing can be one of several” but on the other hand it turns out that if I use enums, then I’ll have to cast it to get its internal value. Here’s an example:
enum Speciality
{
Neurologist=0,
Oncologist=1,
Cardiologist=2,
Gynecologist=3
}
.............
Speciality spec=Speciality.Oncologist;
.............
DisplaySkills(int(spec));
I don’t know, maybe having to cast an enum is a perfectly normal practice and is widely used by programmers, but I thought it would impact the performance (no matter noticeably or not)
I’d go with method
DisplaySkillswhich accepts enum as parameter. Do casting only when call stored procedure.Because when is see
DisplaySkills(int speciality)then there is no connection with specialties declared in some enum. Maybe I should use it this way?On the other hand:
It tells me about all possible parameter values. Also I’d change name to
DisplaySkillsOf(Speciality.Cardiologist)– looks more like English sentence then. And I’d added guard condition to check that passed value contained inSpecialityenum. Otherwise somebody could do thisAnd only inside this method you convert passed enum to int when creating parameter (looks like you are using ADO.NET)
One more tip about creating guard for your method. You can use generic enum wrapper to check if appropriate value was passed