Clean code and refactoring
19 questions in 6 subtopics.
Naming and readability
Rewrite this for readability and explain each change:public List<int[]> getThem(List<int[]> l) {
List<int[]> r = new ArrayList<>();
for (int[] x : l) if (x[0] == 4) r.add(x);
return r;
}
OrderManager, OrderHelper, OrderUtil, OrderServiceImpl and OrderProcessor all exist. What naming conventions would you agree as a team, and how do you apply them?Code smells
Identify the code smells in this method signature and call, and suggest improvements:void process(Order o, boolean sendEmail, boolean dryRun, String a, String b, int t);
process(order, true, false, "EU", "x1", 3);
Refactoring techniques
You must change behaviour in a 400-line legacy method that has no tests. Describe how you refactor it safely before making the change.Refactor this conditional chain with modern Java:double area(Object s) {
if (s instanceof Circle) {
Circle c = (Circle) s;
return Math.PI * c.r() * c.r();
} else if (s instanceof Rect) {
Rect r = (Rect) s;
return r.w() * r.h();
}
throw new IllegalArgumentException();
}
Effective Java items
Why should you prefer try-with-resources over try-finally for closing resources in Java?A class overrides equals but nothashCode. Explain what goes wrong when instances are used as HashMap keys, and how to implement both correctly.Effective Java advises favouring composition over inheritance and uses an example where a subclass of HashSet counts added elements by overriding add and addAll, and the count comes out double. Explain why and how composition fixes it.What guidelines do you follow for Optional and for returning collections from methods? Explain why.Coding standards for a 500-engineer Java organisation, including Effective Java style rules: how detailed should they be, and how do you keep them useful for years?API design for libraries
Design the public API of an internal Java client library for the payments platform that 100 services will use. What principles guide it?You must make a breaking change to a shared library used by 120 services owned by many teams. Plan the migration.The JDK is known for long-term backward compatibility, using practices such as deprecation for removal, preview and incubator features, and strong encapsulation of internals. Which of these practices should guide your company's internal platform APIs over many years?Code review
What do you look for when reviewing a pull request in a Java service?Review this code and list the problems:@Transactional
public void syncAll() {
for (Customer c : customerRepository.findAll()) {
try {
crmClient.push(c);
} catch (Exception e) { }
}
}
No question matches these choices.