No, it’s a pretty good principle, but just like everything in programming, there are no hard rules. Every principle has times when they are appropriate and when they aren’t and it’s our job to find what is most appropriate for the situation at hand. It’s still worth striving towards DRY, but that doesn’t mean that there aren’t many cases where it doesn’t improve the code.
The examples are also pretty contrived, there’s hardly any duplication there and the duplication is very simple and unlikely to change much. DRY is beneficial when the repeated code is complex and will likely need to be changed in the future (eg to fix bugs or to be extended), where repeating the code will be a source of error since every change would then need to be applied to each instance and forgetting one is a problem. The example is trivial enough that I wouldn’t bother refactoring it until it became complex enough to be a problem.
A good principle is to not apply principles too quickly/soon but only when not doing so would introduce complexity or cognitive overhead. YAGNI, basically.
The examples are also pretty contrived, there’s hardly any duplication there and the duplication is very simple and unlikely to change much. DRY is beneficial when the repeated code is complex and will likely need to be changed in the future (eg to fix bugs or to be extended), where repeating the code will be a source of error since every change would then need to be applied to each instance and forgetting one is a problem. The example is trivial enough that I wouldn’t bother refactoring it until it became complex enough to be a problem.
A good principle is to not apply principles too quickly/soon but only when not doing so would introduce complexity or cognitive overhead. YAGNI, basically.