Default values instead error handling

Take a look at the following declaration.

This declaration is from Unity’s “PlayerPrefs” class and this function is an interesting way to solve an exceptional situation. What should this thing do, if the key parameter doesn’t exist in the player prefs? There are a couple of solutions one could think of. We could return an error code indicating a failure. Bleh. We could throw an exception, which is also kinda bleh. But in this solution, the exceptional error case is handled elegantly by using a parameter. Using this function, even if it fails, you don’t need to check for any sort of failure because you’re telling it what to give you if an error occurred. Though this case is exceptional, it might actually be expected from the user’s perspective. Since this method can only fail in one way to the user (either it exists or it doesn’t), one parameter suffices. If it can fail in multiple ways, this could turn into something less concise, unless there was a failure parameter that took a struct of defaults, one per exceptional error case. bleh.

This solution has an issue that might cause some pain for you though. For example, you assume the value exists in the player prefs file but it doesn’t. What you actually get is the default value, so if there’s a bug, you immediately check the player pref’s file, not the code at the call site. In this particular case, the real problem was that the corresponding GetFloat and SetFloat functions actually had a slight typo where the keys were not identical. I wasn’t fetching the key that was being set. But was instead getting the default back. You could imagine the frustration.

The point of this post is to show you that sometimes an elegant clever solution is also a simple solution.