Question

I have a scenario where some of the final variables declared at class level are optional in some cases.

That means I have different constructors. Some of those have to leave the member variables with null values.

Since I have declared the variable as final, I am forced to initialize those in the constructor. So I have to add var = null; statement in the constructor.

But explicitly assigning variables to null is considered to be a bad practice and tools like PMD, reports it as a violation. (Controversial rule in PMD. But do not want to switch it off, since I do not want the null assignment to be practiced in other areas of my code)

Any other suggessions or good practices to achieve this?

Was it helpful?

Solution

You can use constructor chaining, passing null to the values that are not used in your instance. (You can either use the super constructor if we are discussing inheritance, or a different constructor in the same class.) After all I would reconsider the design of your classes, for example extract the optional part to a different class.

OTHER TIPS

Instance variables are assigned default values(null in case of custom object).

So unless you are really assigning some value to your final variables why bother about null assignments?

As user has pointed out in the comment above does not stand good for final variables. So what can be done define a no-arg constructor with all final values set to null.

Now in individual arg constructors place a call to this default constructor by using this() as the 1st statement .. then you can assign values depending on the arguments passed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top