简体   繁体   English

我该怎么写这个更短?

[英]How can I write this shorter?

public static string GetUa(HttpRequest hr)
{
    try
    {
        string visitorBrowser = hr.UserAgent.ToString();
        string originalBrowser = hr.ServerVariables["X-OperaMini-Phone-UA"];
        string anotherOriginalBrowser = hr.ServerVariables["X-Device-User-Agent"]; //novarra

        if (!String.IsNullOrEmpty(originalBrowser))
        {
            return "OPERAMINI " + originalBrowser;
        }
        else
        {
            if (!String.IsNullOrEmpty(anotherOriginalBrowser))
            {
                return "NOVARRA " + anotherOriginalBrowser;
            }
            else
            {
                return visitorBrowser;
            }
        }
    }
    catch
    {
        return "No UA Found";
    }
}

I'd be more concerned with readability. 我更关心可读性。 This seems nicer to me: 这对我来说似乎更好:

var operaAgent = hr.ServerVariables["X-OperaMini-Phone-UA"];
var deviceAgent = hr.ServerVariables["X-Device-User-Agent"];

operaAgent = string.IsNullOrEmpty(operaAgent) ? null : "OPERAMINI" + operaAgent;
deviceAgent = string.IsNullOrEmpty(deviceAgent) ? null : "NOVARRA" + deviceAgent;

return operaAgent ?? deviceAgent ?? hr.UserAgent ?? "Not Found";

Of course, if you didn't need to prefix those strings onto the UAs and didn't need to concern yourself with empty string user agents, then it would simply be: 当然,如果您不需要将这些字符串作为UA的前缀,并且不需要关注空字符串用户代理,那么它只是:

return hr.ServerVariables["X-OperaMini-Phone-UA"] ??
       hr.ServerVariables["X-Device-User-Agent"] ??
       hr.UserAgent ??
       "Not Found";

I don't see any way to significantly shorten that. 我认为没有任何方法可以大大缩短这一点。

One way to save a few lines is to get rid of the braces around the first else: 保存几行的一种方法是摆脱第一个周围的大括号:

if (!String.IsNullOrEmpty(originalBrowser))
{
    return "OPERAMINI " + originalBrowser;
}
else if (!String.IsNullOrEmpty(anotherOriginalBrowser))
{
    return "NOVARRA " + anotherOriginalBrowser;
}
else if (!String.IsNullOrEmpty(visitorBrowser))
{
    return visitorBrowser;
}
else
{
    return "No User Agent Detected";
}

You should be careful about using exceptions for flow control, too. 您也应该小心使用流控制的异常。 statenjason has the right idea. statenjason有正确的想法。

Right now, what you have is clear and legible. 现在,你所拥有的是清晰易读的。 If you're trying to get there with less processing time, I don't think you're going to make it. 如果你想用更少的处理时间到达那里,我认为你不会去做。 If you're trying to get there with fewer lines of code, you can, but it's going to be ugly. 如果你想用更少的代码行来到那里,你可以,但它会变得很难看。

One easy way to shorten it on-screen (same LOC count, -1) is to remove some of your curly braces and not store visitorBrowser : 在屏幕上缩短它的一种简单方法(相同的LOC计数,-1)是删除一些花括号而不是存储visitorBrowser

public static string GetUa(HttpRequest hr)
{
    try
    {
        string originalBrowser = hr.ServerVariables["X-OperaMini-Phone-UA"];
        string anotherOriginalBrowser = hr.ServerVariables["X-Device-User-Agent"]; //novarra

        if (!String.IsNullOrEmpty(originalBrowser))
            return "OPERAMINI " + originalBrowser;
        else
            if (!String.IsNullOrEmpty(anotherOriginalBrowser))
                return "NOVARRA " + anotherOriginalBrowser;
            else
                return hr.UserAgent.ToString();
    }
    catch
    {
        return "No UA Found";
    }
}

To me, this is slightly less readable, but probably still livable. 对我来说,这可读性稍差,但可能仍然适合居住。

Now you can make it really short by using the conditional operator ( ?: ), but it's going to also be really nasty for readability. 现在你可以通过使用条件运算符( ?: :)来使它变得非常简短,但它对于可读性来说也是非常讨厌的。 If I saw code like the following in a code review, I'd make the developer rewrite it for clarity: 如果我在代码审查中看到如下代码,我会让开发人员为了清楚起见重写它:

public static string GetUa(HttpRequest hr)
{
    try
    {
        string visitorBrowser = hr.UserAgent.ToString();
        string originalBrowser = hr.ServerVariables["X-OperaMini-Phone-UA"];
        string anotherOriginalBrowser = hr.ServerVariables["X-Device-User-Agent"]; //novarra

        return !(string.IsNullOrEmpty(originalBrowser)) ? "OPERAMINI " + originalBrowser :
               !(string.IsNullOrEmpty(anotherOriginalBrowser)) ? "NOVARRA " + anotherOriginalBrowser : visitorBrowser);
    }
    catch 
    {
        return "No UA Found";
    }
}

Seriously, please don't do the second example. 说真的, 不要做第二个例子。 (I'm not 100% sure that will compile; I'm writing it off the top of my head on my Mac at the moment. But I'm 99.9% sure it will, and will work, and the next developer will HATE you for it.) (我不是百分百肯定会编译;我现在正在Mac上写下它。但我99.9%肯定它会,并且会工作,下一个开发人员会讨厌你为它。)

Like this, for example: 像这样,例如:

public static string GetUa(HttpRequest hr) {
  try {
    string originalBrowser = hr.ServerVariables["X-OperaMini-Phone-UA"];
    string anotherOriginalBrowser = hr.ServerVariables["X-Device-User-Agent"];
    return
      !String.IsNullOrEmpty(originalBrowser) ? "OPERAMINI " + originalBrowser :
      !String.IsNullOrEmpty(anotherOriginalBrowser) ? "NOVARRA " + anotherOriginalBrowser :
      hr.UserAgent;
  } catch {
    return "No UA Found";
  }
}

Like this (everything else is just extra code doing nothing): 像这样(其他一切只是额外的代码什么都不做):

public static string GetUa(HttpRequest hr) 
{ 
    if (!String.IsNullOrEmpty(hr.ServerVariables["X-OperaMini-Phone-UA"])) 
        return "OPERAMINI " + hr.ServerVariables["X-OperaMini-Phone-UA"])) ; 
    if (!String.IsNullOrEmpty(hr.ServerVariables["X-Device-User-Agent"])) 
        return "NOVARRA " +   hr.ServerVariables["X-Device-User-Agent"])) ; 
    return hr.UserAgent ?? "Not Found"; 
} 

And you should NEVER use exceptions in your normal application flow path. 并且您不应该在正常的应用程序流路径中使用异常。

Here's a condensed version. 这是一个浓缩版本。 Because you're return ing inside each if statement, you can eliminate your else s. 因为你正在每个if语句中return ,你可以消除你的else Also, I eliminated the need for using exceptions for flow. 此外,我消除了使用流异常的需要。

    public static string GetUa(HttpRequest hr)
    {
        string visitorBrowser = hr.UserAgent;
        string originalBrowser = hr.ServerVariables["X-OperaMini-Phone-UA"];
        string anotherOriginalBrowser = hr.ServerVariables["X-Device-User-Agent"]; //novarra
        if (string.IsNullOrEmpty(visitorBrowser))
            return "No UA Found";
        if (!String.IsNullOrEmpty(originalBrowser))
            return "OPERAMINI " + originalBrowser;
        if (!String.IsNullOrEmpty(anotherOriginalBrowser))
            return "NOVARRA " + anotherOriginalBrowser;
        return visitorBrowser;
    }
public static string GetUa(HttpRequest hr)
{
    try
    {
        string visitorBrowser = hr.UserAgent.ToString();
        string originalBrowser = hr.ServerVariables["X-OperaMini-Phone-UA"];
        if (!String.IsNullOrEmpty(originalBrowser)) return "OPERAMINI"+originalBrowser;
        string anotherOriginalBrowser = hr.ServerVariables["X-Device-User-Agent"]; //novarra
        if (!String.IsNullOrEmpty(anotherOriginalBrowser)) return "NOVARRA" + anotherOriginalBrowser;
        return visitorBrowser;
    }
    catch
    {
        return "No UA Found";
    }
}

second if-statment: 第二个if-statment:

return (!String.IsNullOrEmpty(anotherOriginalBrowser) ? ("NOVARRA " + anotherOriginalBrowser) : visitorBrowser);

You can probably use this combined with the first if-statment too 您也可以将此与第一个if-statment结合使用

I don't like when it is doing work that it doesn't have to do. 我不喜欢什么时候做它不需要做的工作。 So I would write it as follows: 所以我会写如下:

   public static string GetUa(HttpRequest hr)
    {
        string browser = hr.ServerVariables["X-OperaMini-Phone-UA"];
        if (!String.IsNullOrEmpty(browser))
            return "OPERAMINI " + browser;

        browser = hr.ServerVariables["X-Device-User-Agent"]; //novarra 
        if (!String.IsNullOrEmpty(browser))
            return "NOVARRA " + browser;

        if (!String.IsNullOrEmpty(hr.UserAgent))
            return hr.UserAgent;

        return "No UA Found";
    } 

A slightly more dynamic .NET 4 approach: 一种稍微动态的.NET 4方法:

    private static readonly Tuple<string, string>[] SpecialUas =
        {
            Tuple.Create("X-OperaMini-Phone-UA", "NOVARRA"),
            Tuple.Create("X-Device-User-Agent", "OPERAMINI")
        };

    public static string GetUa(HttpRequest r)
    {
        return (
                   from specialUa in SpecialUas
                   let serverVariable = r.ServerVariables[specialUa.Item1]
                   where !string.IsNullOrEmpty(serverVariable)
                   select string.Concat(specialUa.Item2, " ", serverVariable)
               ).FirstOrDefault() ?? (
                   string.IsNullOrEmpty(r.UserAgent)
                   ? "No UA Found"
                   : r.UserAgent
               );
    }

This can be customised with additional special UAs very easily by adding further tuples. 通过添加更多元组,可以非常轻松地使用其他特殊UA进行自定义。

It wouldn't be difficult to replace the tuples with something else if you're not running on .NET 4. 如果你没有在.NET 4上运行,用其他东西替换元组并不困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM