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
  • 54,340
  • 18
  • 130
  • 181
nyanev
  • 11,299
  • 6
  • 47
  • 76

4 Answers4

4

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

Reid Mac
  • 2,411
  • 6
  • 37
  • 64
1

Yes, you can call setter in constructor.

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

it's not prohibited

Funtime
  • 2,466
  • 4
  • 20
  • 21
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,735
  • 2
  • 16
  • 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
  • 28,272
  • 7
  • 61
  • 66