Where in the code should I store data that does not change?

I have defined models based on tables in the database. Now there are some models whose data is practically unchanged. For example, the categories of products that are sold on the e-mail site, the cities in which it sends products, etc. They do not change often and, thus, to avoid getting into db, they are currently stored as static variables.

The question is where in the codes should these static variables be. Currently, the ProductCategory class (which is also a model view) defines a static list that, if empty, calls db and loads Product Categories. Similarly, the City class has a similar static list, and so on.

These static lists are then used in the application. I thought about creating a StaticData class, and then saved all the static lists in this class. Now instead

ProductCategory.AllCategories.Find(p => p.Id = 2) 

I will have

StaticData.AllProductCategories.Find(p => p.Id = 2) 

What do you think is the best approach? I also aim for testability and loose code.

Also, is there a better way to achieve them? How do you do something like this in your code?

+5
source share
3 answers

If it is static enough to compile into your code and should never change at run time, you can use a static class, for example, a general template for converting enums to classes .

Something like this should probably work well in your scenario:

public class Vehicle
{
    public static Vehicle Car = new Vehicle("Car");
    public static Vehicle MotorBike = new Vehicle("MotorBike");
    public static Vehicle PeopleMover = new Vehicle("PeopleMover");

    private Vehicle(string name)
    {
        this.name = name
    }
    private string name;
}

enum , , , , ( =), ' , - .

, , ( , ). , .

+3

, Cache .

, , , - :

if [cache contains object or collection I need]
{
   return [object or collection from cache]
}
else
{
   [get object or collection from database]
   [save object or collection in cache]
   return [object or collection from database]
}

, , .

+3

. , , :

  • - .

    , , . , ( , ) . , .

  • Enum.

    , 100% , ... -!

  • Lazy Singleton Static. ( )

    IMHO Lazy Singleton ProductCategory. , , , , . :

    Init. - , . .

    Download on first use . The first time you try to access categories, check if they are loaded or not. If not, the class loads them. In this approach, you spend time the first time you need to access the Product Categories.

    In either of these two approaches, data will be lost after restarting each application pool, so if you release a new version, you will update the data. In the event of a "crash" database update, you can always restart application pools.

+3
source

All Articles