'Avoid repetitive null checking for arguments in functions calling functions
Context:getProfilesFromResponse is a utility function used by websocketMessageHandler to parse the profiles from a websocket message.
What's a better and clean design?
- Should
getProfilesFromResponserepeat the null checks? - Is there a visible performance gain by doing the null checks only once? This is a websocket message callback handler, so its going to be called like 50 times a second due to heavy websocket stream.
- Should
getProfilesFromResponseuseresponse?.dataoverresponse.data?
function getProfilesFromResponse(response) {
// should we add null or undefined checks here as well?
if ('profiles' in response.data) { // should I instead do response?.data
// do remaining data manipulations and return the final data
}
}
function websocketMessageHandler(response) {
if (!response) {
// null checks done here
}
...
...
...
const profiles = getProfilesFromResponse(response);
...
}
My Opinion
- NOPE, we can make a rule for all the functions that are calling
getProfilesFromResponseto do the null checks themselves. The downside is we are assuming things never go wrong, but my counter argument is we do want things to crash so that people actually make sure they don't call the function with null argument. - Not really, it's a O(1) operation. Negligent impact to performance.
- Prefer
response?.dataas its a little more robust. But since we already knowresponseisn't empty, so we can skip it.
Solution 1:[1]
1 - No, you should avoid calling getProfilesFromResponse if response is null, for example, by stopping websocketMessageHandler execution:
function websocketMessageHandler(response) {
if(!response)
return; //< avoid further operations
const profiles = getProfilesFromResponse(response);
// more code here
}
or alternatively:
function websocketMessageHandler(response) {
if(response) {
const profiles = getProfilesFromResponse(response);
// more code here
} else {
// do something in case response is null or undefined
}
}
2 - There is always a benefit avoiding useless operations.
3 - If you properly avoided getProfilesFromResponse to be called with null parameter, you don't have to check again, you also avoided an useless function call...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
