早期回报与嵌套的积极if语句

Joa*_*nge 9 coding-style

这是一些假设的代码示例:

if (e.KeyCode == Keys.Enter)
{
    if (this.CurrentElement == null) {
        return false;}

    if (this.CurrentElement == this.MasterElement) {
        return false;}

    if (!Validator.Exist (this.CurrentElement)) {
        return false;}

    if (!Identifier.IsPictureElement (this.CurrentElement)) {
        return false;}

    this.FlattenObjects(this.CurrentElement);
}
Run Code Online (Sandbox Code Playgroud)

VS

if (e.KeyCode == Keys.Enter)
{
    if (this.CurrentElement != null) {

        if (this.CurrentElement != this.MasterElement) {

            if (Validator.Exist (this.CurrentElement)) {

                if (Identifier.IsPictureElement (this.CurrentElement)) {

                    this.FlattenObjects(this.CurrentElement);}}}}}}

}
Run Code Online (Sandbox Code Playgroud)

您认为哪一个在可读性,维护等方面更好?

此外,第二个示例可以通过括号的不同使用来进行不同的格式化.

SLa*_*aks 14

早期回报更具可读性.

每当你在一个方法中获得超过四到五个级别的嵌套时,就该重构该方法了.

if带有||子句的单个有时可以更具可读性:

if (this.CurrentElement == null
 || this.CurrentElement == this.MasterElement
 || !Validator.Exist(this.CurrentElement)
 || !Identifier.IsPictureElement(this.CurrentElement))
    return false;
Run Code Online (Sandbox Code Playgroud)