How to avoid “too many parameters” problem in API design?

前端 未结 13 1679
别那么骄傲
别那么骄傲 2020-11-27 09:01

I have this API function:

public ResultEnum DoSomeAction(string a, string b, DateTime c, OtherEnum d, 
     string e, string f, out Guid code)
13条回答
  •  暖寄归人
    2020-11-27 09:53

    Use a combination of builder and domain-specific-language style API--Fluent Interface. The API is a little more verbose but with intellisense it's very quick to type out and easy to understand.

    public class Param
    {
            public string A { get; private set; }
            public string B { get; private set; }
            public string C { get; private set; }
    
    
      public class Builder
      {
            private string a;
            private string b;
            private string c;
    
            public Builder WithA(string value)
            {
                  a = value;
                  return this;
            }
    
            public Builder WithB(string value)
            {
                  b = value;
                  return this;
            }
    
            public Builder WithC(string value)
            {
                  c = value;
                  return this;
            }
    
            public Param Build()
            {
                  return new Param { A = a, B = b, C = c };
            }
      }
    
    
      DoSomeAction(new Param.Builder()
            .WithA("a")
            .WithB("b")
            .WithC("c")
            .Build());
    

提交回复
热议问题