Let’s say I have a function that inserts records into a database table with string fields of limited length. In general, at what point should I be truncating strings that are too long for the storage location, in the insert function itself, or at every point in the code where it’s called?
(I’m assuming here that truncation of strings that are too long is more desirable than having an exception thrown.)
I think it depends on where the function is and how accessible it is.
If it’s a private function that just makes up your own SQL library then you can probably get away with truncating it in the function.
If it’s in a library that, say, your team at work all use then perhaps you need to at least parse the string before attempting to insert it.
If it’s a public API, then you shouldn’t be silently truncating anything – throw a meaningful exception instead.