11

I see that Spring has a @Required annotation to mark member variables in beans that must be set.

Is there a best practice for using this?

For instance, might it be better to set these values in the constructor and make these parameters explicitly required (esp. when used outside of Spring)?

Thanks!

Vinnie
  • 12,400
  • 15
  • 59
  • 80

1 Answers1

13

While not referring to the @Required annotation directly, Martin Fowler provides this advice...

He prefers to set object values in the constructor rather than in setters as it will "give you a clear statement of what it means to create a valid object in an obvious place" while it also "allows you to clearly hide any fields that are immutable by simply not providing a setter".

Vinnie
  • 12,400
  • 15
  • 59
  • 80
  • 3
    Further, setting/instantiating variables in the constructor allows you to declare them as final. A final variable, along with providing clear intent of usage (as you suggested), is a step towards achieving immutability (worthwhile if your object needs to be thread-safe). – CaptainHastings Jul 20 '11 at 21:01