Can I configure CheckStyle to error on assignment of local variables (other than initialization)? Basically making all local variables final by default without having to put a ton of final keywords in the code.
In Java declaring a local variable final will make sure it's never assigned to after its initialization. This is very useful and makes it much easier to reason about the code. I'm of the opinion that all variables should be final unless there is some specific reason. Sadly, in Java this requires me to put final in front of everything which imho bloats up the code unnecessarily.
I've noticed that CheckStyle can error on assignment to parameters of functions. This means I don't have to put final in front of those anymore. Is there any way to make CheckStyle give a similar error for any other local variable assignment (other than initialization)? This way I don't need to mark everything as final.
I only see a rule that forces me to put final for variables that can be marked as such.
If for some reason you'd want to assign to a variable multiple times, you'd just have to put a comment to disable CheckStyle on that line. This is kind of like other languages that basically make all variables final by default and you'd have to use a special keyword to make it assignable.
PS: I'm also open to other ways to achieve this in Java without CheckStyle.
There is no way to do this out of the box. I also checked Sevntu Checkstyle (a library with additional checks) which often has what I need but it doesn't appear to have anything for this. I've linked to the checks so you can see for yourself in case I missed anything.
That means you'll have to write the check yourself. It shouldn't be overly difficult. I would copy the code for FinalLocalVariable
which is already doing most the heavy lifting: it is already finding local variables that never change, you simply need to make sure that every variable is like that.
If you do this, maybe consider making a pull request to Checkstyle or Sevntu.
Alternatively, if you are only opposed to using final
because it is verbose, you could consider using Lombok's val
(like Java 10's var
but implicitly final - and available before Java 10). However, if other developers are working on your code base, it would be difficult to enforce using this as part of the build (without writing a check, which you were trying to avoid).