用包含条件的单个方法替换if else语句

时间:2017-10-27 04:35:43

标签: c#

我还在学习C#,但我已经休年假了,我回来工作,看到我的大四学生在他年假前留下的这段代码:

public string GetBasketTotalPrice(string basketLocation)
{
    var basketTotalPrice = _driver.FindElements(CommonPageElements.BasketTotalPrice);
    if (basketLocation.ToLower() == "top")
        return basketTotalPrice[0].Text.Replace("£", "");
    else
        return basketTotalPrice[1].Text.Replace("£", "");           

}

private int GetElementIndexForBasketLocation(string basketLocation)
{
    return basketLocation == "top" ? 0 : 1;
}

我假设不使用if else语句,他希望我使用他的新方法GetElementIndexForBasketLocation。

我的问题只是如何实施此更改?

由于

2 个答案:

答案 0 :(得分:1)

它并不完全清楚您正在寻找什么,但您可以将代码重写为:

    public string GetBasketTotalPrice(string basketLocation)
    {
        var basketTotalPrice = _driver.FindElements(CommonPageElements.BasketTotalPrice);
        int index = GetElementIndexForBasketLocation(basketLocation);
        return basketTotalPrice[index].Text.Replace("£", "");          
    }

    private int GetElementIndexForBasketLocation(string basketLocation)
    {
        return basketLocation.ToLower() == "top" ? 0 : 1;
    }

答案 1 :(得分:1)

看起来他提供给你的方法并没有打电话给ToLower(),而是留给客户做这项工作,这可能会导致错误。

此外,您可以考虑将string.EqualsStringComparison.OrdinalIgnoreCase一起使用,而不是ToLower

在尝试调用字符串上的方法之前添加空检查可能是个好主意,因此您可以抛出ArgumentNullException而不是当前代码将抛出的NullReferenceException

public string GetBasketTotalPrice(string basketLocation)
{
    var basketTotalPrice = _driver.FindElements(CommonPageElements.BasketTotalPrice);

    return basketTotalPrice[GetElementIndexForBasketLocation(basketLocation)]
        .Text.Replace("£", "");
}

private int GetElementIndexForBasketLocation(string basketLocation)
{
    if (basketLocation == null) throw new ArgumentNullException(nameof(basketLocation));
    return basketLocation.Equals("top", StringComparison.OrdinalIgnoreCase) ? 0 : 1;
}