according to Are there guidelines on how many parameters a function should accept?, a method should not have too many parameters. However, some answers suggest this issue can be solved by builder pattern:
Builder b=new Builder();
b.setParm1("a");
b.setParm2("b");
.
.
.
Obj obj=b.createObj();
or encapsulate parameters in a single object.
ObjectParam op=new ObjectParam();
op.param1="a";
op.param2="b";
.
.
.
obj.f(op);
But I doubt if it solves the problem, because I think the methods about just align the parameters at better way (i.e.:from horizontally to vertically), but it doesn't change the nature that the tasks depend on too many parameters. And if I want the chain of parameters have better looking, I can use a new line for each parameter like it:
https://softwareengineering.stackexchange.com/a/331680/248528
so my question is, is "too many parameters" a visual issue (hard to read a long single line of code), or a logical issue (the task nature depends on too much parameters and needs break down)? If it is more about a visual issue, does a new line for each parameter solves the issue?
Best Answer
It is first and foremost a logical issue (which often comes with visual issues, too). The wrong solution to this is by trying only to improve the visual problem by
Encapsulating parameters in an object does not mean to put five parameters in an arbitrary container with some meaningless name like
ObjectParam
. Instead, encapsulating a group of parameters in an object should create a new abstraction (or reuse an existing one). Likeencapsulating three parameters "X,Y,Z" in a parameter "position of type
Point3D
, orencapsulating parameters "startDate, endDate" in an object
DateInterval
orencapsulating parameters
documentTitle, documentText, author
in an objectDocument
grouping these parameters togetherIf the method in stake has a lot of unrelated parameters you cannot come up with a good grouping name, then it has probably too many parameters and too many responsibilities.