Browsed by
Category: Correct code

Correct Code: Pattern for handling user input

Correct Code: Pattern for handling user input

My 15yo daughter has got programming as a subject in her high school. A couple of days ago, she came asking for help. The program she wrote had a bug. While asking her what are the possible options, I came to one simple realization: handling user input has rules. Naimly, her bug was that she was missing the very first step, which I did intuitively. Breaking it down for her is the basis of this post. The pattern When I…

Read More Read More

Correct Java switch statement

Correct Java switch statement

When writing correct code, we should prefer the compiler to do the checks for us, instead of the runtime. While Java’s type system helps us a lot with writing correct code, it has its limitations. Consider an enumeration. public enum AllowedColor { RED, BLUE, YELLOW} A switch statement would look like switch(color) { case RED: System.out.println(“it’s red”); break; case BLUE: System.out.println(“it’s blue”); break; case YELLOW: System.out.println(“it’s yellow”); break;} This looks ok, but what happens when someone adds a new enum…

Read More Read More