Java: Why not allow nulls in methods to represent optional parameters

javamethodsnullparameters

I wanted to follow up on this previous question I asked related to @Laive comment, but I couldn't think of an excellent way to do so without asking another question, so here we go.

With the previous question in context, many users suggested the approach of creating a parameter. The object for a method that has many parameters, others pointed out that plans probably should not have many settings.

I am assuming that the technique has been engineered correctly, and it's been decided that the method should have a reasonable number of parameters, but not only 1 or 2).

Creating a parameter object, if you have optional parameters, needs to have some way in your object parameters. Declaring that a certain as the optional parameter is "not there", and then in your code, you would have to handle that case.

I researched blogs and stuff on the topic, and it seems like it is not preferred to have a method signature that accepts nulls as a flag for "optional value not present".

What is the difference between a param object with an optional field which has a "field not set" value, and a method with explicit parameters for which null is a valid value to represent "optional parameter not set", and why is one acceptable and the other not?

Best Answer

In general it is a bad idea to use null to indicate an optional value. It is a bad idea whether it is for a return value, an object property, a local variable or any other context. So parameters is just one case of a general rule.

So why is it a bad idea? Two reasons:

  • It is not possible in Java to indicate in the type system if null is allowed or not.
  • The default value for an uninitialized reference is null.

This means a reference can be null for two reasons:

  1. There is a bug and the value was not properly initialized
  2. It is intentionally null to indicate the lack of an optional value

Since the code can't distinguish between the two cases, a bug may go unnoticed because the code cannot distinguish a bug from the legitimate value. Therefore other approaches to indicate optional values are preferred.

Using a parameter-object with nullable properties is not really better though since you have the same issue: You don't know if the property is null due to a bug or intentionally. So I disagree with your premise that this is better.

Related Topic