简体   繁体   中英

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:

  1. your object is doing too much on its own, or
  2. 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()等在构造函数中初始化。因为您将没有部分构造的对象,而且看起来也很整洁。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM