Home > Software design >  Validate parameters passed into Constructors during compile time
Validate parameters passed into Constructors during compile time

Time:05-16

In a huge project with tens of thousands of Java files there are a couple of Java classes where developers may pass in strings as parameters to a constructor class I had implemented

public byte[] getProductReport(List<String> products, Date from, Date to) {
    // ... do some stuff before...

    List<ReportParameterDto> reportParameters = new ArrayList<>();
    reportParameters.add(new ReportParameterDto("From (YYYY.MM.DD)", ParameterType.DATE, from));
    reportParameters.add(new ReportParameterDto("To_(YYYY.MM.DD)", ParameterType.DATE, to));
    reportParameters.add(new ReportParameterDto("Products", ParameterType.SELECT, someList));

    return ReportFromCRServerHelper.downloadReport("ProductReporot", reportParameters, ReportFormat.PDF);
}

If a developer uses wrong string values downloading a requested report (from a remote Report server) will fail during runtime.

In this example I would like to have some validation checking - during compilation - in order to avoid these errors before they are found by the customer.

I have API methods to obtain parameter values from a report which I hope to use during compilation of the above method.

In my example the compilation should fail and throw an error highlighting how parameters should look instead:

 "From (JJJJ-MM)" is invalid --> should be "From_(JJJJ-MM)"
 "Products" is invalid --> should be "PRODUCT_LIST"

Can I detect these parameters (used in above ReportParameterDto constructors) through JAVAX annotation processing?

The few tutorials / blogs that I found dealt with validating parameters in method signatures, not the values passed into methods.

Or are there a more elegant tools available?

CodePudding user response:

A compile-time tool like the Checker Framework can validate the arguments to a method or constructor. You annotate the parameter types to indicate the permitted values, and then when javac runs it issues a warning if an argument may not be compatible with the parameter.

If there is a limited number of possible values, then you can use the Fake Enum Checker to treat strings or integers as enumerated values. (Using a Java enum is also a good idea, but may not be possible or convenient because of other code that expects a string or integer.)

If the number of possible values is unlimited, then you can use the Constant Value Checker -- for example, to supply a regular expression that any constant string argument must satisfy.

You can also define your own compile-time validation if you want different functionality than is available in the checkers that are distributed with the Checker Framework.

  • Related