[TIP] Save Delphi program options to an integer
It is a common requirement in programs to have to save several program options, or action permissions, to adapt it to each user. These options can be persisted in an ini, json file or saved in the database, possibly for security reasons and to be accessible to the users of the program, saving it in a database is the best option.
If we have many yes or no options, we would create boolean fields in the database, but can we simplify the number of fields needed? If we have 20 yes or no options in the program, do we create 20 boolean fields in the database? Or can we simplify it.
I share a Delphi tip to do it and also have a more semantic management of the program options. It is about using an enumerative type and building a Set with it, we build the set with the options using the include and exclude functions
//Declare an enumerated type with 32 options to cast as integer
TUserOption = (uoAddCustomer, uoEditCustomer, uoDeleteCustomer, uoReport1, uoReport2, uoReport3, uoReport4, uoReport5, uoReport6, uoReport7, uoReport8, uoAddUser, uoEditUser, uoDeleteUser, uoSeeUsers, uoSendMessages, uoOp17, uoOp18, uoOp19, uoOp20, uoOp21, uoOp22, uoOp23, uoOp24, uoOp25, uoOp26, uoOp27, uoOp28, uoOp29, uoOp30, uoOp31, uoOp32);
//Create a Set using this enumerated type
TUserOptions = set of TUserOption ;
var userOptions: TUserOptions ;
//Begin with an empty Set:
userOptions:= [];
//Add user options with the Include method, take as a parameters the Set variable and the enumerated value:
Include(userOptions,uoAddCustomer);
Include(userOptions,uoReport1);
Include(userOptions,uoReport5);
Include(userOptions,uoReport7);
Include(userOptions,uoSendMessages);
//To persist the set to a Database convert it to a integer value
var option: integer:= Integer(userOptions);
//in this case option:= 33417, save this value in a integer database field
//To retrieve it we do the reverse operation:
userOptions:= TUserOptions(33417);
//To check if an option is present:
if (uoAddCustomer in userOptions) then
//If we want to remove an option from the Set we use the exclude method:
Exclude(userOptions,uoSendMessages);