Today I Learned - Leveraging Records to Eliminate Switch Statements
The Problem
A common approach is to have a function for each command (moveForward, moveBackward, turnLeft, and turnRight).
When it comes to implementation though, they all have a similar pattern:
This works, however, the duplicated switch logic can be annoying to deal with.
During a code review, one of our interns proposed an interesting solution using a dictionary for lookups.
Let's take a closer look.
Possible solution
Instead of leveraging a switch statement, they thought about creating a dictionary where the key was the direction the rover was facing and the value being how to update the rover.
At a high level, it looked something like this:
Even though this looks like a dictionary, I like this approach better for two reasons:
- Explicit key coverage - By defining Record to have a key of
Direction, we're forcing the developer to define options for every direction, not just some of them. - Breaks when type changes - If a new option is added to
Direction, this code won't compile anymore as it doesn't cover every option, which allows us to find bugs faster.
Closing Thoughts
When working with data that requires different access levels, think about leveraging private fields and then providing access through public properties.