Hacker News new | ask | show | jobs
by bchen 5054 days ago
Since long parameter list is considered a code smell, people should be discouraged from writing this kind of code anyways. Namely, this example from the article is in fact a bad practice:

> o.doSomething1("Alfred E. Neumann", "http://blog.schauderhaft.de, 42, "c:\\temp\\x.txt", 23);

As other commenters have pointed out, I think the builder pattern is one of the two solutions I would use. The other solution is to simply create an object that represents the values to be passed in to the method. Consider:

  User user = new User("Alfred E. Neumann");
  user.setLink("http://blog.schauderhaft.de);
  user.setUltimateAnswer(42);
  user.setTempFile("c:\\temp\\x.txt");
  user.setZip(23);
  o.doSomething(user);
Even with named parameters, I would say the latter approach is still superior than having a long parameter list.
2 comments

Named parameters would result in more readable, compact, and efficient code compared to the latter approach.

But yes, long parameter lists (whether represented as argument structs or not) generally indicate a problem.

This, like many of the proposed solutions here exposes the issue that putting the (not particularly) long list of parameters into the ctor, that of not every being able to call doSomething without all the required values. What is the caller of your builder doesn't remember to set the zip and the doSomething method then uses it? You've only really added syntactic sugar and sacrificed functionality.