Limit number of parameters per method?

前端 未结 5 941
离开以前
离开以前 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:39

    I would say it really depends on your case. Are you doing something to the entire set? Validating all the items or aggregating data, for example? In that case, I would pass in an IEnumerable as a single parameter.

    Passing in a lot of parameters can be a good sign of poor separation of concerns (i.e. your method is doing too much), but it sounds like in this case you're passing in a well defined set of items to iterate them in some way. Given the collection initializer syntax in C# 3, I would recommend IEnumerable in pretty much every case over a list of parameters that would be something like Type a, Type b, Type c....

    Of course, if your parameters are actually treated differently, then separating them out makes sense, but I would consider what you're doing in that case. A simple case that comes to mind would be building a tree data structure and having a function to build up the children of a node. A poor syntax might be:

    Node BuildTree( Node parent, Node child1, Node child2...)
    

    I would probably pursue something more like:

    void ConstructChildren( this Node parent, IEnumerable children)
    

    If you can provide more information about your case, though, and what sort of logic you're performing on the parameters, it would probably be easier to see if it's a good candidate for collapsing or refactoring.

提交回复
热议问题