Passing single object vs. passing multiple parameters

后端 未结 4 853
孤街浪徒
孤街浪徒 2021-01-31 03:26

Suppose I have the following

Class A {
    Foo getFoo();
    Bar getBar();
    Baz getBaz();
}

And I need to define a function doStuff

4条回答
  •  [愿得一人]
    2021-01-31 04:01

    Parameter Objects do provide a nice approach to encapsulate related parameters to reduce the total parameter count to any method or constructor. One should be very careful to make sure that the parameter objects do actually contain truly related parameters.

    Actually there are multiple ways of approaching this problem depending on the parameter types you are dealing with. If you are dealing with parameters that are general types like more than one Strings or Ints and there is a potential for a client to actually pass in the wrong sequence of arguments ,it often makes more sense to create custom types ie. create enum with possible values. That can provide good compile time check for your arguments. Another good use of them is you can use them to return complex values from functions. See here.

    Another approach i take a lot of times is to check and see if the work done by the doStuff method be broken down into simpler methods with less dependencies.

    Principally i try to follow Bob Martin's recommendation of a maximum of three parameters. Well he actually say it should be mostly not more than one ! Any increase should have justified reasons. Refer this excellent book : Clean Code

提交回复
热议问题