Default values instead error handling

Take a look at the following declaration.

Although this isn’t particularly interesting, I have come across this little thing. This declaration is from Unity’s PlayerPref’s class and is an interesting way of solving a problem. The problem is “What should this thing do, if the key doesn’t exist in the player prefs?” While attempting to write something very similar, I thought, I could return an error code, which means the output is a parameter. Bleh. I could throw an exception, which is valid too. Which is also kinda bleh. But here, even though retrieving a float is exceptional, it’s handled elegantly because you don’t need to check an error code or write exception safe boiler plate code. You’re specifying what the value should be in case it doesn’t exist. Which is a case that might be expected. In other words, you’re handling the exceptional cases by configuring it. You’re telling it what you want to do in case it fails. Since this method can only fail in one way to the user (doesn’t exist, can’t get it, etc.), one parameter suffices. If it can fail in multiple ways, this could turn into something terrible as all the parameters tell this thing what to do on failure. Perhaps something better, in that case, might be to pass in a “configure” struct. But that’s kinda bleh too.

This actually has an issue that can cause some pain though. When I was using Unity a long time ago, I remember having a bug where I thought the value was in the player prefs, but really it was just the return value. The GetFloat and SetFloat actually had a slight typo where the keys were not identical. You could imagine the frustration. Although this might be equivalent to not checking the error code return value if the declaration was specified that way.

Anyways, the point is that sometimes an elegant simple solution is also a clever one.