Quiz: Comments and Code Formatting in Java: Clean Code Rules

Total: 5 questions

1. 

When is a comment justified in clean code?

When it says what the code cannot: why a non-obvious decision was made, a warning about consequences, an explanation of an external format, the contract of a public API in Javadoc, or a TODO linked to a ticket. Before writing a comment, try to express the same with a method name, an explanatory variable or a constant.

2. 

Why should commented-out code be deleted?

Nobody dares to remove it because it looks important, it quickly stops compiling and nobody knows whether it is still needed. Version control already keeps every old version, so the code can be restored from history if it is ever needed again.

3. 

Why should braces be used for if, else, for and while even with a single statement?

Without braces, the next developer who adds a second line to the body changes the logic: only the first statement belongs to the if, and the indentation of the second one is misleading. With braces, the block boundaries are explicit and adding a line is safe.

4. 

How should a long stream pipeline be formatted?

One operation per line, with each line starting with a dot and indented as a continuation: strings.stream(), then .filter(...), .sorted(), .map(...) and .toList() on separate lines. Each step can then be read, commented out while debugging and reviewed separately.

5. 

How can a team keep code formatting consistent?

Agree on a style once and store it in the repository as formatter configuration: an IntelliJ IDEA code style scheme, an .editorconfig file or a Checkstyle configuration. Let the IDE reformat on save, and add a check such as Checkstyle or Spotless to the build so that unformatted code does not reach the main branch.

Page 1 of 1