This is intended to be a general language-agnostic question. It is written around a weird example simply because I could not find a better way to ask. Also, the "pseudocodes" provided look like a mixture of Java and JavaScript only because those are the languages I'm most familiarized with, but hopefully they will be easy to understand for everyone.
Let's say I have a String
field called tuples
in a database. When the user clicks a button (the Store Numbers button), the function store_numbers
is executed, as follows (in pseudocode):
function store_numbers() {
// Make a bunch of calculations and generate some integer tuples,
// such as (0,1), (4,4) and (-500,0)
// Create a string with those tuples, semicolon-separated,
// with the exact format above, such as
// "(0,1);(4,4);(-500,0)"
// Insert this string in the 'tuples' field of the database (for the given UserID)
}
And this is the only way, in the whole software, that the tuples
field of the database is altered (at least in the current version of the software).
Now, let's say the same user comes back tomorrow and clicks another button (the Calculate Stuff button), and the function calculate_stuff
is executed. This function will read the string tuples
from the database, and is supposed to make various calculations with the tuples. QUESTION: Can I assume the tuples
string is perfectly formatted? Or should I validate the string that came from the database first?
OPTION 1: Assuming it's perfectly formatted:
function calculate_stuff() {
String tuples = // read string from database...
// immediately begin calculations assuming string is perfect
for (String tuple in tuples.split(';')) {
String[] temp = tuple.replace('(','').replace(')','').split(',');
int x = Math.parseInt(temp[0]);
int y = Math.parseInt(temp[1]);
// ...
}
// ...
// If somehow the string was wrong, ugly errors will be thrown,
// and the software will crash.
// But this shouldn't happen, since the string was crafted
// correctly in the store_numbers() function.
}
OPTION 2: Validating it first:
function calculate_stuff() {
String tuples = // read string from database...
// Check if the string is OK first:
if (!is_a_semicolon_separated_list_of_integer_tuples(tuples)) {
error("Oh no! Something terrible happened! How come??");
} else {
// Proceed calculations...
}
}
MY THOUGHTS: Option 1 will not give any decent error message to the user - the software will crash instead. This is terrifying in a UX perspective, but since the string was correctly crafted by the other function, this really should never happen. On the other hand, maybe it doesn't hurt to add the check? Well... Coding the is_a_semicolon_separated_list_of_integer_tuples
is not that hard, but is not ridiculously easy either. What if it was a much more complicated string, whose validation would take hundreds of lines of code?? For something that will never happen?
What are the guidelines for this? What are the good programming practices involved?