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

前端 未结 13 1668
别那么骄傲
别那么骄傲 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:33

    A variant of Samuel's answer that I used in my project when I had the same problem:

    class MagicPerformer
    {
        public int Param1 { get; set; }
        public string Param2 { get; set; }
        public DateTime Param3 { get; set; }
    
        public MagicPerformer SetParam1(int value) { this.Param1 = value; return this; }
        public MagicPerformer SetParam2(string value) { this.Param2 = value; return this; }
        public MagicPerformer SetParam4(DateTime value) { this.Param3 = value; return this; }
    
        public void DoMagic() // Uses all the parameters and does the magic
        {
        }
    }
    

    And to use:

    new MagicPerformer().SeParam1(10).SetParam2("Yo!").DoMagic();
    

    In my case the parameters were intentionally modifiable, because the setter methods didn't allow for all possible combinations, and just exposed common combinations of them. That's because some of my parameters were pretty complex and writing methods for all possible cases would have been difficult and unnecessary (crazy combinations are rarely used).

提交回复
热议问题