优化三元运算符 [英] Optimize ternary operator
问题描述
我遇到了别人写的这段代码。是否推荐或通常使用这种条件运算符?我觉得它不太容易维护-还是我?还有其他替代方法吗?
exp_rsp_status = req.security_violation吗? (dis_prot_viol_rsp&& is_mstr)?
uvc_pkg :: MRSP_OKAY:uvc_pkg :: MRSP_PROTVIOL:req.slv_req.size()?
((is_mst_abort_rsp&& dis_mst_abort_rsp)||
((req.slv_req [0] .get_rsp_status()== uvc_pkg :: MRSP_PROTVIOL)&& dis_prot_viol_b $ b | (is_mst_abort_rsp&& req.is_pci_config_req()&& dis_pcicfg_mst_abort_rsp))
uvc_pkg :: MRSP_OKAY:req.slv_req [0] .get_rsp_status():uvc_pkg :: MRSP_OKAY;
那只是可怕的代码。
- 格式错误。我看不到该表达式的层次结构。
- 即使它具有良好的格式,该表达式也太复杂而无法用人眼快速解析。
- 意图不明确。这些条件的目的是什么?
那你能做什么?
- 使用条件语句(
if
)。 - 提取子表达式,并将其存储在变量中。从重构目录中查看这个好例子。
- 使用辅助功能。如果逻辑复杂,请使用早期的
返回
。没有人喜欢深度缩进。 - 最重要的是,给所有内容起一个有意义的名字。意图应该很清楚,为什么必须要计算某些东西。
请注意:三元运算符没有什么问题。如果谨慎使用,它通常会生成易于消化的代码。避免嵌套它们。如果代码清晰明了,我有时会使用第二级,即使那样,我也会使用括号,这样我的可怜的大脑就不必做额外的循环来破坏运算符的优先级。
代码的读者。I came across this code written by someone else. Is this usage of the conditional operator recommended or commonly used? I feel it is less maintainable - or is it just me? Is there any alternate way of writing this?
exp_rsp_status = req.security_violation ? (dis_prot_viol_rsp && is_mstr) ?
uvc_pkg::MRSP_OKAY : uvc_pkg::MRSP_PROTVIOL : req.slv_req.size() ?
((is_mst_abort_rsp && dis_mst_abort_rsp) ||
((req.slv_req[0].get_rsp_status()==uvc_pkg::MRSP_PROTVIOL) && dis_prot_viol_rsp) ||
(is_mst_abort_rsp && req.is_pci_config_req() && dis_pcicfg_mst_abort_rsp)) ?
uvc_pkg::MRSP_OKAY : req.slv_req[0].get_rsp_status() : uvc_pkg::MRSP_OKAY;
That's just horrible code.
- It's badly formatted. I don't see the hierarchy of the expression.
- Even if it had good formatting, the expression would be way too complex to quickly parse with the human eye.
- The intention is unclear. What's the purpose of those conditions?
So what can you do?
- Use conditional statements (
if
). - Extract the sub-expressions, and store them in variables. Check this nice example from the refactoring catalog.
- Use helper functions. If the logic is complex, use early
return
s. Nobody likes deep indentation. - Most importantly, give everything a meaningful name. The intention should be clear why something has to be calculated.
And just to be clear: There's nothing wrong with the ternary operator. If used judiously, it often produces code that's easier to digest. Avoid nesting them though. I occasionally use a second level if the code is crystal clear, and even then I use parentheses so my poor brain doesn't have to do extra cycles decyphering the operator precedence.
Care about the readers of your code.
这篇关于优化三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!