Java initializing object design

Lets say I have a object foo from class Foo . Lets say class Foo has a lot of fields that characterize its offsprings.

When having so many fields, is it preferred to initialize them all via the constructor of Foo eg.

Foo foo = new Foo(0, 12, 123, 2, 2, (and so on...));

or initialize them in the constructor or method from the class one will be using foo eg.

Foo foo = new Foo();

public void initFoo() {
    foo.setX(1);
    foo.setY(3);
    foo.setH(3);
    (and so on...)
}

I would do everything via the constructor. That way you can't forget to do this and end up with a partially constructed object. Using the constructor leads naturally to making immutable objects, and these are useful in terms of being able to reason about their behaviour (especially in multi-threaded environments)

A follow-up to this would be to use a builder pattern. In this scenario you provide the builder component with the parameters, and the builder can then determine the missing parameters and/or how to construct the object.

eg

FooBuilder fb = new FooBuilder();
fb.setX(1);
fb.setY(2);
// etc...
Foo f = fb.newInstance();

Having said all this, do you need to construct your object with so many parameters ? That sounds like either:

  • your object is doing too much on its own, or
  • those parameters can be combined into other meaningful objects (eg x and y coordinates as a point etc.)

  • In general I would advice you to use the first approach for the sake of loose coupling. It does not matter how many members your class needs to initialize.
    You will need this approach as soon as you start to write unit-tests for non-trivial classes,
    where you will need to mock those members.

    Browse the web for further readings on dependency injection, unit tests, inversion of control and loose coupling if you like to learn more about design decisions related to your question.


    就个人而言,我会继续你的第二个版本,即在构造函数中用setX(),setY()等进行初始化。因为你不会有部分构造对象,并且它看起来很整齐。

    链接地址: http://www.djcxy.com/p/31498.html

    上一篇: Call和Callvirt

    下一篇: Java初始化对象设计