本文介绍了我使用保护子句,并尽量避免else子句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读(例如,从Martin Fowler),我们应该使用guard子句而不是单个返回在(短)方法在OOP。我也读过(从某个地方我不记得)那个else子句应该尽可能避免。

I've read (e.g. from Martin Fowler) that we should use guard clause instead of single return in a (short) method in OOP. I've also read (from somewhere I don't remember) that else clause should be avoided when possible.

但我的同事(我在一个小团队工作,只有3人)强迫我不在方法中使用多个返回,并尽可能多地使用else子句,即使在else块中只有一个注释行。

But my colleagues (I work in a small team with only 3 guys) force me not to use multiple returns in a method, and to use else clause as much as possible, even if there is only one comment line in the else block.

这使我很难遵循他们的编码风格,因为例如,我不能在一个屏幕中查看方法的所有代码。当我编写代码时,我必须先写保护子句,然后尝试将其转换为带多个返回的形式。

This makes it difficult for me to follow their coding style, because for example, I cannot view all code of a method in one screen. And when I code, I have to write guard clause first, and then try to convert it into the form with out multiple returns.

我错了或我应该怎么办

推荐答案

这是可论证的纯粹的审美问题。

This is arguable and pure aesthetic question.

在C和类似语言中历史上避免了早期返回,因为可能会错过在早期返回的情况下通常放在函数末尾的资源清除。

Early return has been historically avoided in C and similar languages since it was possible to miss resource cleanup which is usually placed at the end of the function in case of early return.

鉴于Java有异常,尝试,catch,最后,没有必要害怕早期的回报。

Given that Java have exceptions and try, catch, finally, there's no need to fear early returns.

Personaly,我同意你,这通常意味着更少的代码和更简单的代码流与更少的if / else嵌套。

Personaly, I agree with you, since I do early return often - that usually means less code and simpler code flow with less if/else nesting.

这篇关于我使用保护子句,并尽量避免else子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 02:19