0

I am using the same final constants in different classes, like

class A { private static final String NAME = "Name"; }
class B { private static final String NAME = "Name"; }
class C { private static final String NAME = "Name"; }

I am trying to simplify the code here instead of using the same constants in multiple classes.

In my view I have some ideas,

  1. creating an enum with constants
  2. creating a final class with constants
  3. create a property file with all constants and use read in Java file

Could you give adviseon what is the efficient way to do it?.

or is there any design pattern to use it in an efficient manner?

  • 2
    Are those constants really the same thing (e.g. mathematical constants), or are they different constants that just happen to have the same value (e.g. the name of an operation for logging purposes)? In the latter case, you should not try to fold those constants. – Sebastian Redl Mar 21 '17 at 9:57
  • I think the 3th option will add unecessary complexity to the application. Plus will make the readability and testing a little bit more difficult. As Killian as said KISS and DRY. – Laiv Mar 21 '17 at 19:53
2

You don't need our help on this. The point of not repeating yourself is, well, not repeating yourself (because it increases understanding, reduces refactoring effort, minimizes the likelihood of consistency errors, etc.). All three solutions you propose take care of that.

Also, DRY is not about runtime efficiency - the JVM would happily work with three copies of the same String internally, and things wouldn't be any slower for it. Therefore, all four possibilities are already efficient.

It follows that to choose between these solutions, you have the luxury of conforming to whatever other pressures are at work in your project: Do I already have a convenient property file? Are enum alternatives the coding standard? Choose the way that improves the code base with respect to these higher-level criteria.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.