Вопрос

I have a table UserItems {ID, UserID, ItemID}

Items must be in RAM (not in db table).

What is better for this? As enum with attributes or as dictionary of items?:

enum Items
{
    [InternalParam("x432", 34)]
    Red = 1,
    [InternalParam("x431", 12)]
    Green = 2,
    [InternalParam("x438", 54)]
    White = 3
}

OR

enum ItemsIds {Red=1, Green=2, White=3}
Dictionary<ItemsIds, Item> Items = new Dictionary(){
    {Red, new Item("x432", 34)},
    {Green, new Item("x431", 12)},
    {White, new Item("x438", 54)},
}
Это было полезно?

Решение

If you're absolutely certain that the ids are not going to change and that the ids are and will be linear, the first would be preferable, since you can simply grab the enum by using the id as an ordinal.

Though in my humble opinion, you would be doing yourself a favor to assume that ids can change if you're having to lookup the enum given its item id. My reasoning is like this: Suppose your client is having a problem with the current version of your program, and in it, you have 15 items and therefore 15 enums for each id. The only way to fix the problem is to revert to an earlier version which just so happens to use 14 items and 14 enums. Best case scenario, you simply can't, otherwise you risk to read item with id 15 from the database and your program doesn't have the enum for it.

Of course the worst case scenario is actually updating the program to the earlier version and creating a lot of unexpected hassle. Bottom line: treat items as enum or persisted database data, but NOT BOTH.

If you can't eliminate the need to use item ids coming from the database, you shouldn't be using enums, yes even if you don't think they'll change and yes even if they're only 15 objects you can hold in memory. Go the extra mile. You can load it on program start and nobody will be the wiser.

Лицензировано под: CC-BY-SA с атрибуция
scroll top