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?

Paul Bellora
  • 53,024
  • 17
  • 128
  • 180
nyanev
  • 10,991
  • 6
  • 44
  • 76

4 Answers4

4

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

Reid Mac
  • 2,301
  • 6
  • 34
  • 64
1

Yes, you can call setter in constructor.

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

it's not prohibited

Funtime
  • 2,276
  • 4
  • 19
  • 20
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

Community
  • 1
  • 1
questborn
  • 2,605
  • 2
  • 14
  • 17
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.

MeBigFatGuy
  • 27,804
  • 7
  • 59
  • 64