Question

Java primitives always have a default value in the memory of O (booleans are false = 0). So why is it considered as a bad practise to not initialize them, if they even have a predefined value because of this mechanic? And in arrays, even with initialization of a new int[8], all the values in it arent really initialized, but that isnt frowned upon...

Was it helpful?

Solution 2

ALL instance variables are initialized. If you don't specify a value, the default value is used.

Who says it's bad practice to not initialize instance variables? I tend not to initialize them unless it's to a non-default value, but it's not a big deal either way. It's about readability and reducing "code noise" improves readability. Useless initializing is code noise IMHO.

OTHER TIPS

By explicitly defining a value, it's clear that you intended that value at that point of execution. If not, another reader might interpret it as if you either forgot to initialize this variable or you don't care at that point (and will set it somewhere else later).

In other words, it's some kind of implicit documentation. Generally, it's considered better practice to write verbose code for better readability; i.e. never use abbreviations for methods names, write them out!

Also, if you have to write line comments (//), you can almost always replace them by wrapping the following code into a well-named method. Implicit documentation ftw! :)

Say i am writing a small game and every single entity (enemy, player etc) starts with 100 health, there is no point in using a sethealth(100) method every time a new entity is created.

So basically, imo unless you need to use a certain value other than zero, I would not initialize them. Same goes for booleans, unless you need something to be true right off the bat, no point in touching it.

Its not bad practice, and Ive seen experienced developers who do initialise, and those who dont.

My preference is to initialise as it shows the developer has taken time to consider what the values should be on start up, and is not just relying on the compiler using defaults

It is not bad practice to initialize instance variable of class. But it is bot necessory to initialize it, because if you forgot or not initialize it, default value is assign to it.
Initialization required when we want that class instance variable/s must have some value at the time of initialization of class object.

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