I’ve frequently worked on projects that use a factory to create objects that have been persisted to a database. The type of object is stored in an integer in the database and there is a corresponding #include file to enumerate the types of objects that can be created sorta like this…
enum Products
{
Espresso = 1,
Latte = 2,
Long_Black = 3
};
and can write code like
if(productType == Products::Latte) // Ignore the switch on type, just go with the argument here…
Product::ServeWithMilk();
The problem of course, is with our product list, we have over 30, and are adding them at a fairly regular clip. This means we need to
INSERT INTO Product VALUES (4, ‘Flat White’)
and then add to the enum Product enum as Flat_White = 4. Given the concept that we should update once only, the following script can be used to automatically generate the include file…
declare enumCursor cursor fast_forward for
select typeId, productName
from Product
declare @enumVal AS VARCHAR(10)
declare @enumName AS VARCHAR(50)
declare @line AS VARCHAR(80)
print ‘/** ‘
print ‘ * Product type cursor is autogenerated from sql’
print ‘ */’
print ‘enum ProductType’
print ‘{’
open enumCursor
fetch next from enumCursor into @enumVal, @enumName
while @@fetch_status = 0
begin
set @line = ‘ ‘ + replace(@enumName, ‘ ‘, ‘_’) + ‘ = ‘ + @enumVal
fetch next from enumCursor into @enumVal, @enumName
if(@@fetch_status = 0)
set @line = @line + ‘,’
print @line
end
close enumCursor
deallocate enumCursor
print ‘};’
Save the script as a generateProducts.sql, and use osql to call it as a pre-build step…
osql.exe -E -dCoffeeApp -h-1 -oProductEnum.h -n -i generateProducts.sql -b
This is not all that difficult to do, and keeps the database and the include files in sync. What amazes me about this though is that in four of the seven organisations I’ve recently worked at, nobody has actually done it. The other thing that has really surprised me has been the resistance to my changes to implement it this way. Not from managers - who haven’t actually cared all that much, but by the senior developers in the group! Quite remarkable really. I guess they don’t like handing over that manual control…