Quiz: Meaningful Names in Java: How to Name Variables, Methods and Classes

Total: 5 questions

1. 

What is a meaningful name in Java?

A meaningful name tells why a variable, method or class exists, what it does and how it is used, so the reader does not need a comment or the implementation to understand it. For example, elapsedTimeInDays instead of d, or countExpensiveCars(Car[] cars) instead of getThem().

2. 

Why is accountList a bad name for a Map<String, Account>?

The name lies about the type. A reader expects a list and may call accountList.get(0); on a map this compiles, because get takes an Object, and silently returns null. Names such as accounts or accountsByNumber describe the content without a misleading container word.

3. 

How long should a variable name be?

As long as its scope requires. A variable that lives for a few lines, such as a loop counter i or a lambda parameter in a one-line pipeline, can be short. A field or a public method used across the project needs a name that is clear without context. An awkwardly long name often signals that the method does several jobs.

4. 

How should boolean variables be named?

A boolean name should read as a yes/no question: isActive, hasBonus, canRetry, exists. Avoid negative names such as isNotValid or disableCache, because a condition like if (!isNotValid) makes the reader resolve a double negative.

5. 

How should the components of a record be named?

As nouns without the get prefix. A record component becomes a private final field, a constructor parameter and an accessor at once, so one name appears in three places. For record Money(BigDecimal amount, Currency currency) the accessor is amount(), not getAmount().

Page 1 of 1