Quiz: Code Smells in Java: Lambdas, Streams, Optional and Classic Smells
Study the lesson first: Code Smells in Java: Lambdas, Streams, Optional and Classic Smells
Total: 5 questions
1. What is a code smell?
What is a code smell?
A surface sign in the code that usually points to a deeper design problem: a magic number, a duplicated block, a hard-to-read condition, a lambda twenty lines long. A smell is not a bug, because the code works, but it makes the next change slower and riskier.
2. Why should peek() not be used for logic in streams?
Why should peek() not be used for logic in streams?
According to the JDK documentation, peek() exists mainly to support debugging. The stream may skip it: since Java 9, count() can compute the size directly from the source without running the pipeline. It also runs lazily and possibly in parallel. Put side effects in forEach() or outside the stream.
3. What is the difference between Stream.toList() and collect(Collectors.toList())?
What is the difference between Stream.toList() and collect(Collectors.toList())?
Stream.toList() (Java 16) returns an unmodifiable list, so a later add() throws UnsupportedOperationException. Collectors.toList() does not specify mutability, but in practice returns an ArrayList. When you need a mutable list, use collect(Collectors.toCollection(ArrayList::new)).
4. What is a magic number and how do you fix it?
What is a magic number and how do you fix it?
A literal whose meaning is not obvious from the code, such as 9.81 or 86400. Replace it with a named constant, for example GRAVITY or SECONDS_PER_DAY: the name explains the value and a change happens in one place. For a fixed set of related values, use an enum instead of int or String constants.
5. What is hidden temporal coupling?
What is hidden temporal coupling?
Methods must be called in a particular order, but nothing in their signatures shows or enforces that order, usually because they pass state through fields. Swapping two calls still compiles and fails at runtime. The fix is to let each step return what the next step needs, so the data forces the order, for example Order order = takeOrder(productName); and then prepareProduct(order).