Business logic constants, the best place to define them.

When working with business logic implementation code and you do not want use magic numbers in the code - where is the best place to put all those CONSTANTS ? Django settings file ?

@KenWhitesell Dear Ken, please share your super valuable opinion if you can. Thanks a lot!

Hmmm… One could make the argument that the settings file is code, but I think I understand what you really mean here.

<opinion>
There are some things you might want to consider before making a decision as to how you want to handle these types of values.

  • Are you going to have different installations where those values are different?
  • For any given installation, how frequently may those values change?
  • Do you want to be able to change these values without redeploying an app?
  • Do you want to be able to give a non-programmer the ability to change these values?

If the answer to any of these is “Yes”, then I’d consider making a table for them.

If the answer to all these is a “hard no”, where you can’t envision any situation where any of these might change, then you could consider a settings-like file in the app in which its used, but I would never put them in the system’s settings file. (You can look at the Settings class in django.conf.__init__ to see how Django handles that file - it’s really not that complicated.)
</opinion>

In these types of situations, we typically use a type of EAV pattern where the model consists of columns for the name of the variable, the data type, and columns for text, integer, decimal, and boolean. Anything even potentially needing to be “dynamically modified” gets stored in that table.

The initial values are stored in fixtures to be loaded when the database is initialized. This lets us create different fixtures for different installations and select at deployment-time which set of defaults to use.

1 Like

Thank you very much for such a fast and rich answer!