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?

7
  • 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. Commented Apr 27, 2023 at 6: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 Commented Apr 27, 2023 at 6:19
  • Do you have a specific question about the pros and cons of these approaches? Commented Apr 27, 2023 at 6:53
  • 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. Commented Apr 27, 2023 at 7:37
  • 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 … Commented May 8, 2023 at 9:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.