Legacy Code – How to Introduce New Language Features?

clean codecoding-standardscoding-stylejava

I have a coding style related question. In my example it is java, but I think this can be a generic question regarding languages that are changing rapidly.

I'm working on a java code base which was mainly written targeting java 8. The code was migrated to java 12. By migration I mean the code can run on jdk12, so the necessary library changes/additions were done. However the new language features haven't been used yet (e.g. var keyword).

My question is, what should be the approach to introduce new language elements from readability point of view? How important is consistency?

I have a few possible approaches in my mind.

  1. New language features should be used only in new classes
  2. New language features can be used in newly added parts of existing classes (e.g. a new method), even if the rest of the class is not updated.
  3. When a new language features are added to new parts of existing classes, then the rest of the class should be updated too

I know this question is a bit hard to answer (as coding style questions in general), but still I hope there will be some conclusion.

Best Answer

When in Rome do as the Romans do.

It's nice if an entire code base follows one consistent style. However that will trap it's style in the past.

If you're enchanted by some new fangled style the worst thing you can do is scatter it randomly among code left in the old style.

This is why when you repaint a house a different color you don't just do it where the paint is damaged. You do it room by room.

It's better to make the change within some boundary. Those reading the code should find it easy to predict what style they will find in each place.

Changing the style of working code is a refactoring. Don't refactor without tests. And don't refactor everything at once. Do one room, step back, and ask others what they think.

When you can't do all that, stick with the old style. Only use new language features that blend well with the old style.