From a functional programming or even general point of view, where do you check for undefined values that are essential for functions to work (or if undefined they will throw an exception) - inside or outside (before calling it)
Here are two examples:
First one is where you pass the unchecked potentially undefined value to the function
function callAPIEndpoint(someCookie: string | null | undefined){
if (!someCookie) {
return Promise.Reject(new MissingSomeCookieException);
}
// ... fetch, return res
}
function myReqHandler(req, res) {
return callAPIEndpoint(req.cookies['someCookie'])
}
The other approach were you handle the undefined check and possibly throwing of the exception outside the function:
function callAPIEndpoint(someCookie: string){
// fetch, return res
}
function myReqHandler(req, res) {
const someCookie = req.cookies['someCookie'];
if (!someCookie) {
return Promise.Reject(new MissingSomeCookieException);
}
return callAPIEndpoint(someCookie);
}
I feels wrong to pass potentially undefined or null values as parameters to functions who will throw an exception if undefined or null. To my undersanding it would be best to keep functions to a single responsibility and have another function verify and potentially throw/return the exception.
I hope this question will not be locked or removed as I'm very well aware that you cannot post purely subjective/opinion based questions here, so don't misunderstand it - I'm asking for good code practices or patterns how to handle undefined or exception handling, because after many years of coding and having worked with many people, I still don't see any consistency here and I'm genuinely still in doubt of how to do this.