Weak requirements: how to make sure that the object is initialized

I want to write bean-friendly classes. I observed a tendency (mainly with beans) to move the required parameters to setters from the constructor (and use the method init()when this is done when setting the initial state).

This method concerns me because I want my classes to be usable without a bean infrastructure, like Java objects. I believe that I need to check the correct state of the object in each style of the method statement.

Quick demo for the above:

class A {
    public int x;
    public int y;
    private int sum;

    private boolean initialized = false;

    public void init() {
        sum = x + y;
        initialized = true;
    }

    private void initCheck() {
        if (!initialized) {
            throw new IllegalStateException("Uninitialized object.");
        }
    }

    public int getXMulSum() {
        initCheck();
        return x * sum;
    }

    public int getYMulSum() {
        initCheck();
        return y * sum;
    }

}

Is there a better practice?

+4
source share
2 answers

Given that you do not want to use the framework ...

, . . . .

, , , - , , , . , . Factory, bean. , - bean, .

Builder, .

" ( beans) "

. bean, "" , . , , , , , bean, . .

+3

, , .

, , , .

, , . , . Spring .

, . init(), .

+1

Source: https://habr.com/ru/post/1535314/


All Articles