0

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...)
}
0

3 Answers 3

4

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.

e.g.

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 (e.g. x and y coordinates as a point etc.)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thank you so much! I'll definitely investigate those terms. +1
0

Personally, I would go up with your second version i.e Initializing in constructor with setX(), setY() etc. Because you won't have partial constructed object and also it looks neat and tidy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.