开发者

Benefits of having a Java class with just public static final fields? [closed]

开发者 https://www.devze.com 2023-03-08 10:27 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened开发者_开发知识库, visit the help center. Closed 11 years ago.

I'm reviewing some code from my job from another employee and came across a class consisting of only public static final fields. What is the benefit of this, and how would it be used? My guess is that it makes it easy to retrieve info from XML tags. Any other ideas or knowledge?


It's a common Java idiom to define (sort of) constants, to avoid harcoding fixed ('magic' - probably duplicated and hard to refactor) values in code.

https://softwareengineering.stackexchange.com/questions/59642/best-practices-for-constants

http://www.javapractices.com/topic/TopicAction.do?Id=2

Java enumerations vs. static constants

Best practice for global constants involving magic numbers


Its a common (albeit bad) way in Java to have a collection of constant values for one reason or another. Also, if its older Java code, it was a common way to implement enums before there was language support for them


Generally we use it to hold constants value.

For example:

public static final String USER_ADMIN="admin";

Also See

  • what-is-the-best-way-to-implement-constants-in-java ?


It is used for holding constants which will be required by single/multiple source files.

public static final String username="admin";

But to achieve this, I would rather use interface, instead of class. Since any class can implement it, it will help more in my purpose. Although this choice depends on requirements.

0

精彩评论

暂无评论...
验证码 换一张
取 消