Find the bug · #10 · Empty and null Medium Java
New users get an error instead of a greeting
The app greets users by nickname, and new users who skip the nickname crash it.
On this page
The report
The home screen greets users by nickname. Since the sign-up form made the nickname optional, new users who skip it see an error screen instead of the home page.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Greeter {
// "Hi, <nickname>!" or, without a nickname, "Hi, <first name>!"
static String greeting(String first, String nickname) {
String name = nickname.trim().isEmpty() ? first : nickname.trim();
return "Hi, " + name + "!";
}
}Read it, then pick a line.
When the nickname field is skipped, what does the form store: an empty string, or nothing at all?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
System.out.println(Greeter.greeting("Asha", " Ash "));
try {
System.out.println(Greeter.greeting("Ravi", null));
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}It prints
Hi, Ash! NullPointerException
It should print
Hi, Ash! Hi, Ravi!
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 calls nickname.trim() before checking whether there is a nickname at all. Users who skip the field have null, and calling a method on null throws a NullPointerException. The check handles a blank nickname, but not a missing one.
The fix
1class Greeter {2 // "Hi, <nickname>!" or, without a nickname, "Hi, <first name>!"3 static String greeting(String first, String nickname) {4 String name = nickname.trim().isEmpty() ? first : nickname.trim();4 String name = (nickname == null || nickname.trim().isEmpty()) ? first : nickname.trim();5 return "Hi, " + name + "!";6 }7}How you’d find it
- Reproduce with what a skipped field really stores:
null, not"". It throws a NullPointerException. - The stack trace points at line 4. The only object a method is called on there is
nickname. - List the cases the code has to cover: a nickname, a blank one, and none. Only the first two were handled.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
check(Greeter.greeting("Ravi", null).equals("Hi, Ravi!"), "no nickname");
check(Greeter.greeting("Ravi", " ").equals("Hi, Ravi!"), "blank nickname");
check(Greeter.greeting("Asha", "Ash").equals("Hi, Ash!"), "nickname");Where else this bites
name.equals("admin")throws whennameis null;"admin".equals(name)doesn’t.- Any optional field added to a form after users already exist.