TNG / ArchUnit

A Java architecture test library, to specify and assert architecture rules in plain Java
http://archunit.org
Apache License 2.0
3.19k stars 289 forks source link

Feature suggestion: Expose synchronized blocks in core API #1315

Open bannmann opened 4 months ago

bannmann commented 4 months ago

There is a widespread practice of avoiding unnecessarily exposing your synchronization locks, i.e. using synchronized(myPrivateField) instead of public synchronized void myMethod(). (For background, see e.g. this SO question or the rationale for using a related Lombok feature.)

I think ArchUnit could be used nicely to write rules around this, for example:

As far as I can see, however, ArchUnit does not model the existence of synchronized blocks or which locks they use.

Now of course there are static code analyzers that do some of this (e.g. Error Prone with its @GuardedBy annotation). Still, I believe it's worthwhile to support this concept in ArchUnit for the following reasons:

So, could this be added?

Note: in theory, it would also be possible to model what accesses are done inside a synchronized block, enabling rules similar to what ErrorProne does (see link above). IMO this is not required. However, when refactoring the model now in order to add the minimal feature, one should probably take care to not create any obstacles for a future addition of the larger feature.