null arguments

Avoid Null Arguments

null arguments

 

Null arguments add to the noise and take away from the clarity of our code. 

Consider:

  var customer = CreateCustomer(details, null, null, contact);

Do the two null arguments add anything to the understanding? No, on the contrary, they only confuse. 

They are there because CreateCustomer() requires four parameters.

The second and third parameters must be optional if they can accept nulls as valid input. Nulls are not meaningful input.

Since these parameters are optional, could we leave them out altogether? 

  var customer = CreateCustomer(details, contact);

Is that not much nicer?

We have removed the nulls, and fellow programmers reading our code will no longer need to wonder what the nulls were hiding. 

OK, how do we best remove these optional, nullable parameters?

We could expose an overload requiring only the first and fourth parameters:

  public Customer CreateCustomer(CustomerDetails details, Contact contact)
  {
     // ...
  }

How would we write this new CreateCustomer() function?

As I see it, we have a couple of options:

  1. We could copy and paste the code we have in the original 4-parameter CreateCustomer(). We would remove any references of what were the second and third parameters, or
  2. We could write a forwarding overload that calls the original CreateCustomer() with the nulls:
  public Customer CreateCustomer(CustomerDetails details, Contact contact)
  {
     return CreateCustomer(details, null, null, contact);
  }

The second option is much better since it promotes code reuse and minimises the number of lines of code. Why? Say, CreateCustomer() is a large function comprising 50 lines[1] of code. When we copy and paste those lines into our new two-parameter overload, we need to retain, say, 25 lines of code—we only required the other 25 lines for parameters 2 & 3, which we have removed. 

Let’s tally up the lines of code for each solution:

  1. Copy & Paste: 50 + 25 = 75
  2. Forwarding Overload: 50 + 1 = 51

Ladies and gentlemen, we have a winner! 

In this example, Copy & Paste has nearly 50% more lines than Forwarding Overload. Even worse, with Copy & Paste, we also modified the code and may have introduced bugs.

Indiscriminate Copy & Paste is the bane of our industry.

Please see null arguments for the programming sloppiness that it is. They are noise and detract from the clarity of our code. Try to avoid them if you can. 

Footnotes:

[1] I am not declaring 50 lines of code to be an acceptable length for a function. IMO, that is way too long. How short should a function be?

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply