代码之家  ›  专栏  ›  技术社区  ›  Hunter

避免多重If中的céBest practice

  •  4
  • Hunter  · 技术社区  · 14 年前

    假设我们要检查地址行。包括地址行1,地址行2,城镇,国家,邮政编码 如果输入了任何一个属性,则所有其他字段都是必需的。 如果没有输入,则不必触发验证。

    为了达到这个目的,我用了两行If语句。

    if(AddressLine1 != null || AddressLine2 != null || Town != null || Country != null)
    {
        if(AddressLine1 != null && AddressLine2 != null && Town != null && Country != null) == false
         {
              return false;
         }   
    }
    

    注意:我正在使用c#。有什么语言结构我可以利用。

    4 回复  |  直到 14 年前
        1
  •  6
  •   Jon Skeet    14 年前

    好吧,空合并运算符可以帮助处理第一个:

    if (AddressLine1 ?? AddressLine2 ?? Town ?? Country != null)
    {
        if (AddressLine1 == null || AddressLine2 == null ||
            Town == null || Country == null)
        {
            return false;
        }
        // Presumably there's more here
    }
    

    不过,您可能需要编写一些助手方法:

    if (IsAnyNonNull(AddressLine1, AddressLine2, Town, Country))
    {
        if (IsAnyNull(AddressLine1, AddressLine2, Town, Country))
        {
            return false;
        }
    }
    

    public static bool IsAnyNonNull(params object[] values)
    {
        return values.Any(x => x != null);
    }
    
    public static bool IsAnyNull(params object[] values)
    {
        return values.Any(x => x == null);
    }
    

    当然,你还有两个 if 声明-但我认为这基本上是必要的。

        2
  •  8
  •   Dave D    14 年前
    private bool IsAddressValid(params string[] addressParts)
    {
        return addressParts.Any(p => p != null) ? addressParts.All(p => p != null) : true;
    }
    

    如此称呼:

    var addressValid = IsAddressValid(AddressLine1, AddressLine2, Town, County);
    
        3
  •  6
  •   Douglas    14 年前

    var fields = new object[] {AddressLine1, AddressLine2, Town, Country};
    return fields.All(f => f == null) || fields.All(f => f != null);
    
        4
  •  0
  •   munificent    14 年前

    定义如下:

    public static bool SameNullness(params object[] values)
    {
        int nullCount = 0;
        foreach (var value in values)
        {
            if (value == null) nullCount++;
        }
    
        return nullCount == values.Length;
    }
    

    然后像这样使用它:

    SameNullness(AddressLine1, AddressLine2, Town, Country);