Reputation: 1941
This is kind of a very simple question, but I'm really interested to know what is the good practice.
I have an system including a logging sub-system. Logs contain informations about users ID. The logging simplified is like this:
log.RegisterEvent(eventType, userID, eventDetails);
Some events are system events and they have not associated an userID. As the user IDs are positive integers, I consider that 0 means that the event doesn't reffer to a user:
log.RegisterEvent(eventType, 0, eventDetails);
But putting 0 there is just... not right. I thought of using enums, like:
enum UserID
{
None = 0
}
But is it ok to have an enum with only one value? It is better to use a static constant? Or it is anothe better way?
Upvotes: 6
Views: 7480
Reputation: 61952
I don't like your enum because most developers will not expect that (UserIDEnum)42
is used, since it's not a "defined" value of the enum type.
Also the idea of a "magic" constant is not very appealing to me.
This seems an obvious case for a nullable type, namely int?
(also called Nullable<int>
). Most developers will understand that if the int?
is null (HasValue
is false) it means absence of a user ID, and if it's 42, then that's the user ID.
So change the second parameter to type int?
. and calls will look like this:
log.RegisterEvent(eventType, null, eventDetails); // no user ID in this case
log.RegisterEvent(eventType, userID, eventDetails); // variable userID is automatically "lifted" from int to Nullable<int>
Upvotes: 3
Reputation: 14672
Change the logging sub-system to define an overload that takes no user id.
In that overload you could just code a 0 as it is now the only place it will be used.
Upvotes: 1
Reputation: 1500865
"User ID" doesn't sound like a natural kind of enum to me. It's not like there's a natural bounded set of users globally.
A constant value would make more sense:
const long UnknownUserId = 0;
There are cases where an enum with a single value would make sense, but it would almost always be for future expansoin.
Upvotes: 8
Reputation: 106836
It is better to use a constant - otherwise you would have to cast the enum value when used because the API really expects a number. Enums are for closed sets of values and user ID's do not belong to this category.
Upvotes: 5
Reputation: 48568
Yes what use is an enum when there is no diversity in there.
Upvotes: 0