0

Is using more than once the same String value in class methods always means creating constant field in class? Two examples:

Approach #1: Field

private static final String PROP_NAME = "prop.name";

and usage:

private String getPropertyNameValue(){
  return propService.getProperty(PROP_NAME);
}

Approach #2: Without field

private String getPropertyNameValue(){
  return propService.getProperty("prop.name");
}

Which way is better? If the manner of using them is equals - what are pros and cons of each?

Thanks.

2
  • 1
    Primarily opinion based, but my 2c: if it's used in multiple places, use the constant. If it's used in just that place, use the literal (you're just introducing indirection otherwise; having to look in two places to find out which property is returned is extra cognitive load). Mar 17, 2017 at 9:00
  • 1
    @michal : private static final String PROP_NAME = "prop.name"; Declaring variable as static final will help you to create a CONSTANT, Only one copy exists which can be accessed anywhere. So if you want a constant PROP_NAME and want share in mutltiplce (with in class or out side of class) then you should go with static final. Mar 17, 2017 at 9:39

0

Browse other questions tagged or ask your own question.