vendredi 17 février 2017

Custom Validator for Static Use of Reflection vs. Custom Rule in SonarQube (Java)

There may be some related questions, but I think my situation is peculiar enough to justify a question on its own.

I'm working on a historically grown huge Java project (far over one million LOC), where reflection is used to display data in tables - reflection is not used for dynamically changing the displayed data, but just for using some kind of short cuts in the code. A simplified part of the code looks like this.

TableColumns taco = new TableColumns(Bean.class);
taco.add(new TableColumn("myFirstMember"));
taco.add(new TableColumn("mySecondMember"));
 ...
List<Bean> dataList = getDataFromDB(myFilterSettings);
taco.displayTable(dataList);

So the values of the table cells of each row are stored in an instance of Bean. The values for the first cell comes from calling itemOfDataList.getMyFirstMember() (so here comes the reflection part of the code). The rendering of the table cells is done depending on the return type of the itemOfDataList.getMyFirstMember().

This way, it's easy to add new columns to the table, getting them rendered in a standard way without caring about any details.

Problem of this approach: when the getter name changes, the compiler doesn't notice and there will be an exception at runtime in case Bean.getMyFirstMember() was renamed to Bean.getMyFirstMemberChanged().

While reflection is used to determine which getter is called, the needed info is in fact available at compile time, there are no variables used for the column info.

My goal: having a validator that will check at compile time whether the needed getter methods in the Bean class do exist.

Possible solultions:

  • modifying the code (using more specific infos, writing an adapter, using annotations or whatever that can be checked at compile time by the compiler), I explicitely don't want a solution of this kind, due to the huge code basis. I just need to guarantee that the reflection won't fail at runtime.

  • writing a custom validator: I guess this shouldn't be too complex, but I have no real idea how to start, we use eclipse as ide, so it should be possible to write such a custom validator - any hints for a good starting point?

  • as we use SonarQube for quality checking, we could also implement a custom rule checking if the methods do exist - not completely sure if such a custom rule is possible (probably yes)

  • maybe other solutions that will give a fast feedback that some tables won't render correctly after some getter methods were renamed

What I'm asking for:

  • what will be easier in this situation: writing a custom validator for eclipse or writing a custom rule for SonarQube?

  • hints where to start either approach

  • hints for other solultions

Thanks for your help.





Aucun commentaire:

Enregistrer un commentaire