Lambda Recipe for attribute validation of Collection of POJOs

Printer-friendly versionPDF version

So here is a recipe you can use to validate a POJO attribute for some value. In my case I will show you how to check if attributes were set to null. But you can expand on the example as an exercise for yourself.

So here is the template method for a single object and a collection of objects:

<t, r=""> void verifyValueNotNull(final T object, final Function<t, r=""> objectValueGetterMethod,
            final String errorMessage) throws ANullEncounteredException {
      if (object != null) {
         final boolean result = Objects.nonNull(objectValueGetterMethod.apply(object));
         if (!result) {
            throw new ANullEncounteredException(errorMessage);
         }
      } else {
         throw new ANullEncounteredException("The POJO object you supplied was null.");
      }
   }
 
<t, r=""> void verifyValueNotNull(final Collection<t> listOfObject,
            final Function<t, r=""> objectValueGetterMethod, final String errorMessage) throws BadConfigurationException {
      final ANullEncounteredException parentException = new ANullEncounteredException(
               "Null values in POJO found where valid values were expected.");
      listOfObject.stream().forEach(o -&gt; {
         final boolean result = Objects.nonNull(objectValueGetterMethod.apply(o));
         if (!result) {
            parentException.addSuppressed(new ANullEncounteredException(errorMessage));
         }
      });
      if (parentException.getSuppressed().length &gt; 0) {
         throw parentException;
      }
   }
</t,></t></t,></t,></t,>

This is how you can call the above methods:

// For single object
this.verifyValueNotNull(aPersonPojos, PersonPojo::getPersonId,
               "The person object is required to have a person id.");
// For a collection of objects like a list
this.verifyValueNotNull(listOfPersonPojos, PersonPojo::getPersonId,
               "The person object is required to have a person id.");

So feel free to use this recipe. Note the use of suppressed exceptions to report Bulk exceptions. I like to have the option of Bulk exceptions and the suppressed mechanism provides one. If you take exception to this way of reporting bulk exceptions, even the JDK is doing this in its URL classes. (Need to search for precise reference again, but I have seen it, so I believe already.)

Tags:

Top level category:

Add new comment