English 中文(简体)
用一种方法写“回归”的完美方式是什么。
原标题:What is the perfect way to write "return" in a method

我不像方法一样有几条回归线。 因此,我设定了一种回报价值,其结果非常明显。

但是,在我撰写“副渔获物”机制时,我必须设定公开展示结果。 因为,如果我回过审判结果,汇编者就会产生错误,而且说并非所有的代码都具有回报价值。 请参看result = string。 沃尔特说,为结束这一方法而雇用的是无法达到的代码。 因此,这里就是一个例子。

<>> 在一种方法中写“回归”的完美方式是什么?

    public static string PingThatAddress(string hostAddress)
    {
        try
        {
            Ping ping = new Ping();
            PingReply pingreply = ping.Send(hostAddress);

            string result;
            if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
            {
                result = "Address: " + pingreply.Address + "
"
                     + "Roundtrip Time: " + pingreply.RoundtripTime + "
"
                     + "TTL (Time To Live): " + pingreply.Options.Ttl + "
"
                     + "Buffer Size: " + pingreply.Buffer.Length + "
";
            }
            else
            {
                result = string.Empty;
            }

            return result;
        }
        catch (Exception pingError)
        {
            Debug.Fail(pingError.Message + " " + pingError);
        }
        //compiler error: THERE IS NO RETURN VALUE here?
    }
最佳回答

你们可以这样做:

public static string PingThatAddress(string hostAddress)
{
    string result = string.Empty;
    try
    {
        Ping ping = new Ping();
        PingReply pingreply = ping.Send(hostAddress);

        if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
        {
            result = "Address: " + pingreply.Address + "
"
                 + "Roundtrip Time: " + pingreply.RoundtripTime + "
"
                 + "TTL (Time To Live): " + pingreply.Options.Ttl + "
"
                 + "Buffer Size: " + pingreply.Buffer.Length + "
";
        }

    }
    catch (Exception pingError)
    {
        Debug.Fail(pingError.Message + " " + pingError);
    }
    return result;
}

然后,仅仅确保<代码>result适用于在例外情况下具有意义的事项。

如果你试图坚持对你发出警告的话,那么:

public static string PingThatAddress(string hostAddress)
{
    try
    {
        Ping ping = new Ping();
        PingReply pingreply = ping.Send(hostAddress);

        string result = string.Empty;
        if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
        {
            result = "Address: " + pingreply.Address + "
"
                 + "Roundtrip Time: " + pingreply.RoundtripTime + "
"
                 + "TTL (Time To Live): " + pingreply.Options.Ttl + "
"
                 + "Buffer Size: " + pingreply.Buffer.Length + "
";
        }
        return result;

    }
    catch (Exception pingError)
    {
        Debug.Fail(pingError.Message + " " + pingError);
    }
    return string.Empty;
}

你们在这里不能有两种方式: 你的不使用多条<代码>的人工标准(<>return>/code>)声明,可能给你带来麻烦。

问题回答

其中一些建议,包括所接受答复的第一部分,以及最初的问题,都有可能重新产生不正确的结果,特别是在例外情况下。

问题——我们已多次看到这种情况发生——即,如果你有单一的回报价值,那么对方法逻辑的微小改动将不可避免地导致采用原方法作者未预见的守则,从而导致收益在方法上被错误地确定多次或根本没有确定。

There are definitely times when you have to collect a value for returning to the caller and then perform some additional tasks in the method subsequent to that, but by and large that should be the exception rather than the rule.

After tracking down far too many bugs that were introduced by the desire to have a single return value, our development standards now dictate that return will be used unless absolutely necessary and the reason for not doing so must be thoroughly documented in the code along with warnings for subsequent modifiers.

这种做法的另一个好处是,如果对这种方法的逻辑进行修改,使新的法典在回归逻辑上产生“漏洞”,则汇编者将自动通知你。 采用单一回报价值要求开发商视力检查每一种可能的密码途径,以核实没有遗漏任何东西。

Finally, rather than having a return value outside of the exception, we require that the appropriate default value be returned from within the exception handler. This way it is crystal clear as to what will happen in the event of an exception.

因此,在我们的环境中,你的法典是:

public static string PingThatAddress(string hostAddress)
{
    try
    {
        Ping ping = new Ping();
        PingReply pingreply = ping.Send(hostAddress);

        if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
        {
            return "Address: " + pingreply.Address + "
"
                 + "Roundtrip Time: " + pingreply.RoundtripTime + "
"
                 + "TTL (Time To Live): " + pingreply.Options.Ttl + "
"
                 + "Buffer Size: " + pingreply.Buffer.Length + "
";
        }
        else
        {
            return string.Empty;
        }
    }
    catch (Exception pingError)
    {
        Debug.Fail(pingError.Message + " " + pingError);
        return string.Empty;
    }
}

因此,你声称,正在帮助您的点到该出境点的if statement (或其他方案流程说明) 是t t 实际上是的出境点? 该控制声明与<代码>return声明之间的唯一区别是return声明实际上更加明显、更容易读、更可维持、更小的错误。 而且,由于返回声明将达到任何水平,你可能会重复控制声明的次数。

最终想发表返回声明的唯一原因是处理资源——从一开始便拿走你声称的资源。 这一点在C/C++中更为常见。 (即便在C++中,没有工作也不太麻烦。) 在 Java,你可以依靠例外机制和<代码>明确说明处理资源(在 Java7,“资源行业”特征)。

还有其他理由选择<代码>return说明。 一种是能够标明变数最终值:因为汇编者知道,return(或为此而扔 throw)是方法的终点,因此,你可以更容易地插入最后变量。 最终变量——一旦被人使用——确实容易读成法典,并有助于你避免犯错误。

  boolean someErrorCondition = true;
  final int setSomething;
  for (int i = 0; i < 8; i++) {
      if (i == 7) {
          setSomething = 11;
          break;
      }

      if (someErrorCondition) {
          return;
      }
  }

这种做法与你的做法不相干,因为汇编者将抱怨尚未确定的最后变量(这是整个想法,不会变成无效的国家)。

优秀开发商和语言设计师的体力选择了多份返回声明。 我将紧急建议任何人不要朝其他方向走下去。

如有例外情况,你不退还价值。

多次返回声明使遵守你的守则更加容易。 这样,你就立即看到不同的方法返回点。 反之,一个回归结果使你不得不在改变后找到使用该地的地方。 这使得更难以跟踪这种方法的自然流动。 但是,不管怎么说,人们通常对风格的偏好视而不见。 确保你不采取两种做法。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签