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

前端 未结 13 1585
别那么骄傲
别那么骄傲 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条回答
  • Why not just make an interface that enforces immutability (i.e. only getters)?

    It's essentially your first solution, but you force the function to use the interface to access the parameter.

    public interface IDoSomeActionParameters
    {
        string A { get; }
        string B { get; }
        DateTime C { get; }
        OtherEnum D { get; }
        string E { get; }
        string F { get; }              
    }
    
    public class DoSomeActionParameters: IDoSomeActionParameters
    {
        public string A { get; set; }
        public string B { get; set; }
        public DateTime C { get; set; }
        public OtherEnum D { get; set; }
        public string E { get; set; }
        public string F { get; set; }        
    }
    

    and the function declaration becomes:

    public ResultEnum DoSomeAction(IDoSomeActionParameters parameters, out Guid code)
    

    Pros:

    • Doesn't have stack space problem like struct solution
    • Natural solution using language semantics
    • Immutability is obvious
    • Flexible (consumer can use a different class if he wants)

    Cons:

    • Some repetitive work (same declarations in two different entities)
    • Developer has to guess that DoSomeActionParameters is a class that could be mapped to IDoSomeActionParameters
    0 讨论(0)
提交回复
热议问题