Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good design to call private methods inside a constructor?

Say I have the following class:

public class FormContainer {

    @EJB
    private ExternalDao externalDao; // uses dependency Injection

    private final OrderForm orderForm;

    private final List<OrderFormContent> formContents;

    public FormContainer(OrderForm orderForm) {
        this.orderForm = orderForm
        initializeOrderForm();
    }

    private void initializeOrderForm() {
        formContents = externalDao.getFormContents(orderForm);
        // similar for any other properties
    }

    // getters & setters
}

I am using this class to be able to hold all the fields that I will need to refer through the application. I am still learning good design and bad design practices so I am wondering if this bad design to initialize the properties of orderForm.

If so, how could it be improved?

like image 505
Beto Avatar asked Aug 10 '16 01:08

Beto


2 Answers

It's OK.

The important rule to remember is not to allow this to "escape", which means don't let the instance be passed, directly or implicitly due to anonymous/inner classes, to another "process" (defined in the broadest terms).

The reason is that your instance may not be completely initialized when the other process gets it, which can lead to inconsistencies and weird bugs.

like image 118
Bohemian Avatar answered Oct 22 '22 08:10

Bohemian


It's ok to call private methods from your constructor to initialize some data that used inside the class. Just be sure that your methods have no "side-effects" like long-time methods that user of your class would probably not expect with just calling your constructor.

If you have such methods, maybe you should extract Inititialize method that user of your class will use when he will be ready for it.

like image 21
Nerlin Avatar answered Oct 22 '22 08:10

Nerlin