1

I am validating input data in setter method and don't want to validate it again in constructor. I wonder if calling the setter in the constructor is good idea?

4 Answers 4

4

Calling a setter from a constructor works just fine. Promotes code reuse.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, you can call setter in constructor.

Sample() {
    setName("name");
}

it's not prohibited

Comments

1

You can do that. It's possible, but I would also suggest you to check forum link.

This post should give you idea about Construtor Injection vs Setter Injection link

Comments

1

Generally considered safe, with the following caveat:

the only possible trouble you can get into is if the setter (or any method you call from a constructor) is overridden in a sub class. To be absolutely safe (paranoic?), make sure that all methods called from a constructor are final.

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.