代码重构,以摆脱代码重复

时间:2010-11-04 14:00:49

标签: c# .net

我有以下类结构:

public class Result
{
   protected int Code {get; set;}
   protected List<string> Messages {get; set;} 
   protected Result ();

   public static Result Success (int code, List<string> messages)
   {
    Result result= new Result();
    result.Code=code;
    result.Messages=messages;
    return result;
   }

}

public class ResultWithName: Result
{
  protected ID {get; set;}

  protected ResultWithName ()
  {
  }

  public static ResultWithName Success (int code, List<string> messages, string name)
  {
    ResultWithName result= new ResultWithName();
    result.Code=code;
    result.Messages=messages;
    result.Name=name;
    return result;
  }

}

如果只有一个静态方法,但是有几个静态方法,问题就可以了,我感兴趣的是如何使代码更清晰优雅。 谢谢

1 个答案:

答案 0 :(得分:8)

使用参数定义构造函数,而不是在Success方法中设置内联属性。然后在构造函数中设置属性,因为每个属性都在继承链中调用。

public class Result
{
    protected int Code { get; set; }
    protected List<string> Messages { get; set; }
    protected Result(int code, List<string> messages)
    {
        Code = code;
        Messages = messages;
    }

    public static Result Success(int code, List<string> messages)
    {
        Result result = new Result(code, messages);
        return result;
    }

}

public class ResultWithName : Result
{
    protected string Name { get; set; }

    protected ResultWithName(int code, List<string> messages, string name) :
        base(code, messages)
    {
        Name = name;
    }

    public static ResultWithName Success(int code, List<string> messages, string name)
    {
        ResultWithName result = new ResultWithName(code, messages, name);
        return result;
    }

}