Are instance initializers good or bad?

Posted by berry120 on Stack Overflow See other posts from Stack Overflow or by berry120
Published on 2011-01-13T00:08:03Z Indexed on 2011/01/13 0:53 UTC
Read the original article Hit count: 120

Filed under:

I personally quite like instance initializers - I use them to assign default values to things such as collections so when writing constructors I don't have to remember to assign them the same default values each time. It seems quite elegant to me - avoids annoying NPE's popping up and avoids duplicate code. A private method doesn't seem as nice because a) it can't assign values to final fields, b) it could be run elsewhere in code and c) the method still needs to be explicitly called at the start of each constructor.

However, the flip side with others I have spoken to is that they're confusing, some people reading the code might not understand what they do or when they're called and thus they could cause more problems than they solve.

Are proper use of these initializers something to be encouraged or avoided? Or is it an "each to their own" case?

© Stack Overflow or respective owner

Related posts about java