4 ms·
function foo(customerId, itemId, orderId) { if(!customer[customerId]) throw new Error("Customer with id=" + customerId + " does not exist"); if(
by z3t4 2y ago
function foo(customerId, itemId, orderId) {
if(!customer[customerId]) throw new Error("Customer with id=" + customerId + " does not exist");
if(!item[itemId]) throw new Error("Item with id=" + itemId + " does not exist");
if(!order[orderId]) throw new Error("Order with id=" + orderId+ " does not exist");
}
Just an example of how you can detect errors early with defensive programming.
- antifa 2y agoAs oppose to a zero cost build time check, that's 3 expensive runtime DB checks, plus an account and a member could have the same ID, so it might run anyways but on the wrong DB rows.
- z3t4 2y agoYou made two points that are correct in theory, but in practice those lookups would/could take micro-seconds, and the bug would be detected within minutes in a production environment. And it would take five minutes or less to patch.
- klysm 2y agoYeah this is exactly why using primitive types for ids is bad. If you encode it in the type system then you cannot make this error and don't need to check it at runtime.
- z3t4 2y agoMost bugs are found at runtime. The static analysis mostly finds silly errors that are easy to fix. A great type system do make it easier to write spaghetti code though, and you can have one letter variable names - naming is difficult.