重构代码并开发干净的代码

时间:2019-01-19 02:48:12

标签: c# asp.net .net c#-4.0

我的dto如下:

public class DaysDetails
{
 public bool Sun {get;set;}
 public bool Mon {get;set;}
 ...
 public bool Sat {get;set;} //All 7 days of the week
}

我有一种检查日期是否已检查并建立逗号分隔的字符串格式的方法。例如:如果选中了星期日和星期一,则输出为“ 0,1”(数字对应于天)

pubic string ConstructDays(DaysDetails d)
{
 StringBuilder constructDays = new StringBuilder();
 if(d.Sun == true)
  { 
    constructDays.Append("0");
  }
 if(d.Mon == true)
 {
   constructDays.Append("1");
  }
 ..... //So on for all seven days
 string day = Convert.toString(constructDays);

 if(day != string.Empty && day[0] == ",")
   day = day.Remove(0,1);
 return day;
}

我需要将此函数转换为更易于维护的代码和简化版本。有什么可以改善的?

4 个答案:

答案 0 :(得分:5)

您可以通过将每个布尔值转换为int并加入结果集合来简化代码。

public class DaysDetails
{
    public bool Sun { get; set; }
    public bool Mon { get; set; }
    public bool Sat { get; set; }
}

public string ConstructDays(DaysDetails d)
{
    var week = new[]
    {
        Convert.ToInt32(d.Sat),
        Convert.ToInt32(d.Sun),
        Convert.ToInt32(d.Mon),
    };
    return string.Join(",",  week);
}

或者如果您要查找的不仅仅是0/1:

public string ConstructDays(DaysDetails d)
{
    var week = new[]
    {
        d.Sat ? 0 : -1,
        d.Sun ? 1 : -1,
        d.Mon ? 2 : -1,
        //...//
    }.Where(x => x != -1);
    return string.Join(",",  week);
}

答案 1 :(得分:0)

遍历类的属性,例如:

pubic string ConstructDays(DaysDetails d)
{
 int Idx = 0;
    string days = "";
    var obj = new DaysDetails ();
    foreach (var p in obj .GetType().GetProperties())
    {   days += (bool)p.GetValue(obj ) ? (days=="" ? Idx.ToString() : ","+Idx.ToString()) : "";
        Idx++;
    }
return days
}

答案 2 :(得分:0)

定义一个标志枚举来存储您的值:

[Flags]
public enum Days
{
    None = 0,
    Sun = 1,  // 0
    Mon = 2,  // 1
    Tue = 4,  // 2
    Wed = 8,  // 3
    Thu = 16, // 4
    Fri = 32, // 5
    Sat = 64  // 6
}

您可以这样设置所选日期:

var days = Days.None;

if (some condition)
    days |= Days.Mon;

if (some other condition)
    days |= Days.Wed;

if (yet another condition)
    days |= Days.Sat;

并根据设置的标志生成值,如下所示:

static public string ConstructDays(Days days)
{
    return string.Join(",", Enum.GetValues(typeof(Days))
                                .Cast<Days>()
                                .Where(d => days.HasFlag(d) && d != Days.None)
                                .Select(d => Math.Log((int)d, 2)));  // 1,3,6
}

答案 3 :(得分:0)

我建议两件事:制作一个将布尔值转换为int表示形式的单独方法,并重写ToString method而不是生成单独的ConstructDays方法。

public class DaysDetails
{
    public bool Sun {get;set;}
    public bool Mon {get;set;}
    ...
    public bool Sat {get;set;} //All 7 days of the week

    public override string ToString() {
        //formatted string
        return $"{GetNumberRepresentationOfBool(Sun)},{GetNumberRepresentationOfBool(Mon)},{GetNumberRepresentationOfBool(Sat)}"
    }
}

public int GetNumberRepresentationOfBool(bool value) {
    return value ? 1 : 0
}

//printing the value
Console.WriteLine(dayDetailsObject.ToString());