避免重复的null检查功能中的参数调用函数
上下文:getProfilesFromResponse
是websocketMessageHandler
使用的实用程序函数从WebSocket消息中解析配置文件。
什么是更好,干净的设计?
getProfilesFromresponse
重复NULL检查吗?- 仅通过一次零检查一次可见的性能增益吗?这是一个WebSocket消息回调处理程序,因此由于沉重的WebSocket流,它将被称为50倍。
getProfilesFromResponse
使用响应?.data
wenders> wendment.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);
...
}
我的意见
- 不,我们可以为调用
getProfilesFromResponse
的所有功能制定规则,以自己进行零检查。缺点是我们假设事情永远不会出错,但是我的反论点是,我们确实希望事情崩溃,以便人们实际上确保他们不会用null参数调用功能。 - 不是真的,这是O(1)操作。对性能的疏忽影响。
- 更喜欢
响应?.data
作为其更强大的功能。但是,由于我们已经知道响应
不是空的,因此我们可以跳过它。
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
getProfilesFromResponse
repeat 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
getProfilesFromResponse
useresponse?.data
overresponse.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
getProfilesFromResponse
to 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?.data
as its a little more robust. But since we already knowresponse
isn't empty, so we can skip it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1-不,您应该避免调用
getProfilesFromResponse
如果响应
是无效的,例如,通过停止websocketMessockegeageHandler
execution> excution> execution:或bes 2-
有:2-始终是避免无用操作的好处。
3-如果正确避免使用null参数调用 getProfiles ,则不必再次检查,您还避免了一个无用的函数调用...
1 - No, you should avoid calling
getProfilesFromResponse
ifresponse
is null, for example, by stoppingwebsocketMessageHandler
execution:or alternatively:
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...