Quiz: Clean Methods in Java: Small, One Job, Few Parameters

Total: 5 questions

1. 

What does it mean that a method should do one thing?

All statements of the method serve the single purpose named in its name, and you cannot extract another method from it that is more than a restatement of the code. If the body can be split by blank lines into parts that each deserve a heading, such as validate, save and notify, the method does several things.

2. 

What is command-query separation?

A rule that a method either does something or answers a question, but not both. A command changes state and returns void; a query returns a value and changes nothing. Queries can then be called any number of times in any order. A getter that changes the object breaks the rule.

3. 

What is a flag argument and how do you get rid of it?

A flag argument is a boolean parameter that selects one of two behaviors inside the method, as in render(true). It shows that the method does more than one thing and hides the meaning at the call site. Split the method into two with descriptive names, for example printInvoiceAsPdf() and printInvoiceAsText(), or use an enum if there are more than two variants.

4. 

How many parameters should a method have?

Ideally zero, one or two; a third needs a reason, and more than three should be grouped into a parameter object. Values that always travel together, such as x and y, form a concept: makeCircle(Point center, double radius) instead of makeCircle(double x, double y, double radius). Since Java 16 a record makes such an object a one-line declaration.

5. 

What is a hidden side effect of a method?

A change the method makes beyond what its name promises, such as checkPassword() that also calls Session.initialize(). A caller who only wants to check the password resets the session without knowing it. Either rename the method to say what it does or, better, move the extra action to the place where it belongs.

Page 1 of 1