Limit number of parameters per method?

前端 未结 5 927
离开以前
离开以前 2021-02-19 07:57

Assuming the parameters are all the same type, is there a rule of thumb in regards to the number of parameters for a method? Im just wondering where I should draw the line and

5条回答
  •  终归单人心
    2021-02-19 08:34

    I try to limit it to 4 or so. Some people say less, some say more.

    The alternative to tons of parameters would be to create an operation class, i.e. replace:

    func(boo, far, lint, pizza, flags);
    

    with

    var action = new DoSomethingObject(boo, far, lint);
    action.Food = pizza;
    action.Go(flags);
    

    This has a few advantages over the function:

    • If some parameters are optional, you can expose them as properties (such as pizza above).
    • If your function takes that many arguments, chances are it does a lot, and could be broken into smaller functions. A class helps you do this cleanly.

提交回复
热议问题