bulletproof code best practices
-
I'm updating a database and want to write well-formed code. The user attempts to add an item to the db. Items must be unique by name; the item already exists. I check this in my code. Question: Which is better: 1] My AddNewItem routine first checks to see if the proposed item exists. Only if it does not will it call an AddItem routine 2] My AddNewItem routine simply calls an AttemptAddNewItem routine. It is that routine's job to handle the checking. i.e. (pseudo-code only): 1]
sub AddNewItem
if !CheckforExisting() then
AddItem()
else
'warn user
end if
end subsub AddItem
'adds new record to db
end functionfunction CheckForExisting
' checks for existing item
end function2]
sub AddNewItem
AddItem()
end subsub AttemptAddItem
if !CheckforExisting() then
'adds new record to db
else
'warn user
end if
end functionfunction CheckForExisting
' checks for existing item
end function________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)
-
I'm updating a database and want to write well-formed code. The user attempts to add an item to the db. Items must be unique by name; the item already exists. I check this in my code. Question: Which is better: 1] My AddNewItem routine first checks to see if the proposed item exists. Only if it does not will it call an AddItem routine 2] My AddNewItem routine simply calls an AttemptAddNewItem routine. It is that routine's job to handle the checking. i.e. (pseudo-code only): 1]
sub AddNewItem
if !CheckforExisting() then
AddItem()
else
'warn user
end if
end subsub AddItem
'adds new record to db
end functionfunction CheckForExisting
' checks for existing item
end function2]
sub AddNewItem
AddItem()
end subsub AttemptAddItem
if !CheckforExisting() then
'adds new record to db
else
'warn user
end if
end functionfunction CheckForExisting
' checks for existing item
end function________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)
It depends what you want to do - if someone tries to add an item that has the same unique identifier, do you want to treat it as editing the current item, or ignore it ? What sort of load are you expecting this program to have ? That is, how many database calls a second do you expect ? If this were a web app, I'd have a return code from the stored proc I called to insert tell me if the item already existed, so I only made one round trip to the database, then I'd deal with telling the user based on that code. Christian Graus - Microsoft MVP - C++