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

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

    In addition to manji response - you may also want to split one operation into several smaller ones. Compare:

     BOOL WINAPI CreateProcess(
       __in_opt     LPCTSTR lpApplicationName,
       __inout_opt  LPTSTR lpCommandLine,
       __in_opt     LPSECURITY_ATTRIBUTES lpProcessAttributes,
       __in_opt     LPSECURITY_ATTRIBUTES lpThreadAttributes,
       __in         BOOL bInheritHandles,
       __in         DWORD dwCreationFlags,
       __in_opt     LPVOID lpEnvironment,
       __in_opt     LPCTSTR lpCurrentDirectory,
       __in         LPSTARTUPINFO lpStartupInfo,
       __out        LPPROCESS_INFORMATION lpProcessInformation
     );
    

    and

     pid_t fork()
     int execvpe(const char *file, char *const argv[], char *const envp[])
     ...
    

    For those who don't know POSIX the creation of child can be as easy as:

    pid_t child = fork();
    if (child == 0) {
        execl("/bin/echo", "Hello world from child", NULL);
    } else if (child != 0) {
        handle_error();
    }
    

    Each design choice represent trade-off over what operations it may do.

    PS. Yes - it is similar to builder - only in reverse (i.e. on callee side instead of caller). It may or may not be better then builder in this specific case.

提交回复
热议问题