2

I am currently working on a legacy code in Java 1.6 and i found that they have a Constants Interface in the Utils package (Is a quite old Webapps) enter image description here

Well, some of the classes import the interface and some just implements it. While i am unable to make some major fixes in the project i would like to use the same solution for every classes that is using this class (almost everything in the projects calls for it).

The content of the class is just a few hundreds of Strings, some static and final and some just public.

Which option is the better approach for this sort of Constants file? extends, implements or just a basic import?

Grismak
  • 192
  • 16
  • 1
    `implements` was an old hack, please don't do that anymore. `import` is much better. If the number of imports is truly huge, you can consider using a global wildcard (`*`) to import many constants at once. – markspace Apr 27 '23 at 06:10
  • yeah, is rare to see it in current code that´s partly why i am a little bit lost, as for imports, some classes are quite crazy but i have to do a few patches, not rework the whole project – Grismak Apr 27 '23 at 06:19
  • Do you have a specific question about the pros and cons of these approaches? – tgdavies Apr 27 '23 at 06:53
  • @tgdavies Well, it would be great to know the pros and cons of the three options in legacy code in order to obtain an homogeneous solution for this sort of interfaces. That being said, markspace recommends Import above implements which is in it´s own way an answer – Grismak Apr 27 '23 at 07:12
  • 2
    extends and implements should be used rather for achieving polymorphism or implementing specific design patterns. You are clearly "just" reaching for the specific values, therefore static import seems like the way to go. – fascynacja Apr 27 '23 at 07:37
  • Thanks for your answer @fascynacja i will go that way. I have in the backlog a major update for this project but it´s so far way that more than the backlog is the backyard. – Grismak Apr 27 '23 at 07:40
  • 2
    Since you wrote “*some static and final and some just public*”, it’s worth clarifying that all fields declared in an interface are implicitly `public`, `static`, and `final`, without the need to declare. You may add the redundant modifiers or omit them, but it’s strongly recommended to be consistent, as declaring these modifiers only on some of the fields obfuscates the fact that all fields have the same modifiers. Besides that, @fascynacja is right, don’t implement this interface, use `import static …` – Holger May 08 '23 at 09:31

0 Answers0