“Proper” function manners and etiquette

Rezaul Hoque
2 min readAug 15, 2016

--

The first few lines of any well behaved function should be argument validation. Fail fast, fail early is not only the motto in the startup world, but the same mantra works when writing a well groomed function. Once you set up the expectations and constraints it also narrows down the behaviour matrix that you need to test.

Usually most of the argument checks are very cheap and hence they won’t hurt performance but would give you additional guards.

Let’s take an example. Here we have this innocent function, which takes in a personId and a Person data object. What is the problem with this, you ask?

Line 9 can throw Null Reference exception, if the argument personData passed in was null.

Null Reference exception is considered to be a billion dollar mistake claimed by Tony Hoare, who originally introduced the concept.

Hence doing argument validation is important, to ensure rest of the code which depends on this can take a solid assumption on what are the valid values.

So, any good developer would add the argument validations as follows:

However a good lazy developer would just use a helper library which does this throw for you when the condition is met to guard the expectation.

You can use one of the many argument validators out there to properly groom your functions.

The validator used in the samples above is something I have written for myself so that I can remain lazy. You can find the code for the validator at github here or get the nuget here.

Disclaimer: Opinions expressed are solely my own and do not express the views or opinions of my employer.

If you liked this post you might like this as well:

--

--

Rezaul Hoque

By day, I work at Wave helping reduce the burden of small business owners. By night, I fight evil code. In a prior life, I spent a decade at Microsoft.