Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relying on default field initialisation - is bad programming style? [closed]

Tags:

I was given a link to the official oracle documentation: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

where it is said:

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

I want to emphasis this part:

Relying on such default values, however, is generally considered bad programming style.

But, oh boy, this is, I would say, a fundamental part of the language specification knowing that instance variables have default values. Why on earth this is a bad programming practice if it is widely used even in Java SE libraries source code?

like image 514
Andremoniy Avatar asked Oct 18 '19 14:10

Andremoniy


People also ask

What is the default value of an object that has not been initialized?

In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables aren't given a default value. You can declare but not use an uninitialised local variable. In Java, the default value of any object is null.

What is the default value of variable in Java?

Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor.


1 Answers

Simple: relying on default values does not communicate intent.

Did you really want that field to start with 0, or did you forget to assign a value?!

And of course, a null reference is half of the two things you need to run into a nullpointer exception.

Finally, using defaults implies that you have non final fields. Which you avoid where possible.

The only counter argument is: why write down things that you don't have to? But I think the listed disadvantages trumpet that, thus assigning 0 to a field explicitly is better than leaving it to the compiler.

like image 178
GhostCat Avatar answered Sep 20 '22 17:09

GhostCat