Java has enough of a reputation for being verbose without programmers writing constructors that take nine or ten parameters. Technically, a constructor or other unit can take more than two hundred parameters, but that’s clearly way too much for everyday use.

Having that many parameters is obviously bad, especially if most of them are all of the same type, as it becomes easier to get confused about the order of the parameters. And of course, if they’re all of the same type you should probably be using an array or collection to pass them around.

However, having just one more parameter than strictly necessary can also be bad, and possibly a sign that you have unwittingly and unnecessarily duplicated a few important lines in your project.

In an integrated development environment (IDE) like NetBeans, you can do an inspection that flags units in your project with eight or more parameters. That should probably be reconfigured to some lower number, like maybe five.

In the Java edition of Building Maintainable Software, Joost Visser advises keeping the number of parameters to no more than four.

The same guideline probably applies to almost all other programming languages, like C#, Scala and even FORTRAN and COBOL. The issue is perhaps moot in languages like Malbolge.

Soon after I read that chapter in Visser’s book, I looked in one of my projects and did some refactoring to comply with that guideline.

I had an exception constructor that took five parameters, and I thought of a couple of ways to get that down to four. I also came up with an auxiliary constructor that takes only three parameters and fills in a fourth.

That would be a good example for this article, except that the domain of the project is a simple but unfamiliar subject. The problem domain needs to be something simple and familiar.

Last week, working on a programming exercise for another simple but much more familiar topic, I found a less dramatic example, in which I reduced a 3-parameter constructor to take just two parameters.

The exercise is a simple payroll processing program. Even if you’ve never had a job that you have to “punch a clock” for, you should have no problem understanding the exercise.

#java #code-duplication #parameter #software-development

Too Many Parameters in Java Might Indicate Subtle Duplication
2.15 GEEK