javainheritanceconstructorpmd

final optional member variable in Java classes


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?


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.