The benefits of having no or few parameters in a method

I’m going over the multi-video series on refactoring a mortgage calculator. Mosh says to basically group methods by similar activity (MortgageCalculator and MortgageReport), and he shows us how to pull out similar parameters and turn them into fields in those classes and then remove them as parameters from the methods. He says that what you want in these cases is to have as few parameters in the methods as possible, turning as many as you can into fields to be shared by methods inside of the class. I get HOW to do this, but I’m not quite sure WHY this structure is better than it was before refactoring. Can anyone give me some pointers on the benefits of writing code in this way over the way it started? Thanks!

In general, the more parameters that a method has, the more complicated it is to understand the method. This is especially true when the parameters have the same type. For example, consider this method:

int doSomething(boolean isGood, boolean isTrue, boolean isBeautiful) { ... }

Now the callers have to put three booleans in order which can look like this:

int result = doSomething(true, false, true);

It is really difficult to read that code and remember what order the parameters were in and it increases the chances of making a mistake. For example, imagine going “wait, was the second parameter isGood or isBeautiful…” and trying to review this code. Nightmare.

In contrast, suppose the booleans were part of the state on an object and then we could just call doSomething with no parameters:

int result = someObjectWithState.doSomething();

See how you are much less likely to make a mistake there?

Here is an article that is effectively borrowing from Joshua Block’s Effective Java on the topic:

If you have the time, I highly recommend reading Effective Java since it has very good wisdom on writing good Java code. I also recommend Uncle Bob’s Clean Code series which is generically useful across all programming languages.