Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-6555

Allow @Immutable classes to validate their properties upon construction

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 2.5.0-beta-3
    • Component/s: ast builder
    • Labels:
      None

      Description

      Currently classes annotated with @Immutable are not allowed to create their own constructor. Instead a map-based and an ordered-based constructor is added by the ImmutableASTTransformation

      However it would be great if there was some way to validate the arguments that are used to populate the immatable object. This would allow the developer to use @Immutable to build value objects allowing them to assert that certain properties are set, certain properties have a certain value, etc...

      A way of implementing this improvement that I can think of is to allow the developer to create his own constructor, relying on the skills of the developer to keep the object immutable

      Another way would be to allow the developer to specify an 'afterPropertiesSet' method in the @Immutable annotation f.e.

      @Immutable(validationMethod="afterPropertiesSet")
      class MyClass{
        private afterPropertiesSet(){
        //some validation of the fields that have been set in the constructor
        }
      }
      

      This method would be called in the constructors as the last statement.

      Perhaps other solutions exist as well.

        Attachments

          Activity

            People

            • Assignee:
              paulk Paul King
              Reporter:
              janbols Jan Bols
            • Votes:
              5 Vote for this issue
              Watchers:
              6 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: