Java Code Quality – Are init() Methods a Code Smell?

code smellcode-qualityjavaobject-orientedobject-oriented-design

Is there any purpose for declaring an init() method for a type?

I'm not asking whether we should prefer init() over a constructor or how to avoid declaring init().

I'm asking if there is any rationale behind declaring an init() method (seeing how common it is) or if it's a code smell and should be avoided.


The init() idiom is quite common, but I have yet to see any real benefit.

I'm talking about types that encourage initialization via a method:

class Demo {
    public void init() {
        //...
    }
}

When will this ever be of use in production code?


I feel it may be a code smell since it suggests the constructor does not fully initialize the object, resulting in a partially created object. The object should not exist if it's state isn't set.

This makes me believe it may be part of some kind of technique used to speed up production, in the sense of enterprise applications. It is the only logical reason I can think of having such an idiom, I'm just not sure how it would be beneficial if so.

Best Answer

Yes, it's a code smell. A code smell isn't something that necessarily always needs to get removed. It's something that makes you take a second look.

Here you have an object in two fundamentally different states: pre-init and post-init. Those states have different responsibilities, different methods that are allowed to be called, and different behavior. It's effectively two different classes.

If you physically make them two separate classes you will statically remove a whole class of potential bugs, at the cost of maybe making your model not match the "real world model" quite as closely. You usually name the first one Config or Setup or something like that.

So next time, try refactoring your construct-init idioms into two-class models and see how it turns out for you.