Video in progress

What is wrong with giving a method a `boolean` flag argument, and how do you fix it?

A flag argument means the method really does two different things, and at the call site it isn't visible what true/false means. It is usually better to split it into two separate, clearly named methods or to use an enum.

📖 Answer

Read the call site:

reportService.generate(userId, true, false);

What is true? What is false? You can't tell without opening the IDE. And inside:

void generate(long userId, boolean asPdf, boolean sendEmail) {
    if (asPdf) { ... } else { ... }
    if (sendEmail) { ... }
}

That is four different behaviors in one method, and every new flag doubles the combinations.

Ways to fix it:

  1. Two methods:
byte[] generatePdf(long userId);
String generateHtml(long userId);
  1. An enum, if there are many variants or they come from configuration:
byte[] generate(long userId, ReportFormat format);
  1. Separate the responsibilities: sending an email is not the job of generating a report, so notifier.send(report) is on the caller's side.

General signals: if you can't describe the method name without the word "and", if the argument count goes above 3, or if there are consecutive parameters of the same type (String, String, String), they are easy to swap, and it is time for a parameter object or a record.