To test incoming data for string values that are too large for the "database" (MS Access), I could do this:
private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
invItem = TruncateVerboseStringMembers(invItem);
. . .
}
private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
const int DESC_MAX_LEN = 35;
const int VENDOR_ID_MAX_LEN = 10;
const int VENDOR_ITEM_MAX_LEN = 12;
if (invItem.Description.Trim().Length > DESC_MAX_LEN)
{
invItem.Description = invItem.Description.Substring(0, DESC_MAX_LEN);
}
if (invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN)
{
invItem.vendor_id = invItem.vendor_id.Substring(0, VENDOR_ID_MAX_LEN);
}
if (invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN)
{
invItem.vendor_item = invItem.vendor_item.Substring(0, VENDOR_ITEM_MAX_LEN);
}
return invItem;
}
...where TruncateVerboseStringMembers()
is always called, even though normally all conditions will fail (strings will not be too long), or I could do it like this:
const int DESC_MAX_LEN = 35;
const int VENDOR_ID_MAX_LEN = 10;
const int VENDOR_ITEM_MAX_LEN = 12;
private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
if ((invItem.Description.Trim().Length > DESC_MAX_LEN) ||
(invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN) ||
(invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN))
{
invItem = TruncateVerboseStringMembers(invItem);
}
. . .
}
private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
if (invItem.Description.Trim().Length > DESC_MAX_LEN)
{
. . .
...where TruncateVerboseStringMembers()
is only called when it needs to swing into action.
Or something fancier, where, if any strings are too long, I pass an array of bool
to TruncateVerboseStringMembers()
.
Which is preferred?