Explain the init method in Java?

1.5K    Asked by AishwaryaJhadav in Java , Asked on Oct 6, 2022

 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?


Answered by Aditi Ishii

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 of the init method in java: pre-init and post-init. Those states have different responsibilities, different methods that are allowed to be called, and different behaviour. 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.



Your Answer

Interviews

Parent Categories