Kross
Kross

Reputation: 5

Are there way to use properties files without hard coding property keys in code?

I have tried using property files, but in the keys are hardcoded in my java file.

I had tried to write different property class but in getter method i need to use key of property and still keys are harcoded.

Upvotes: 0

Views: 339

Answers (2)

jaco0646
jaco0646

Reputation: 17066

As a general programming rule, if you don't want A to know about B, you can always introduce C to manage the relationship between them (a layer of indirection).

So rather than A --> B you have A <-- C --> B.

You can't avoid the fact that some component must understand the parameters of the relationship, but you can control where that knowledge lives. In enterprise applications, managing properties is often the responsibility of a dependency injection container.

Upvotes: 2

GhostCat
GhostCat

Reputation: 140427

Think about it: you have two sides here.

On the one hand side, you have your code that is supposed to "deal" with certain elements. On the other side, you have your property files, that contain "additional information".

Now: there needs to be a way to "connect" these two sides. You see, the point of your code is "I want to do X, and for that I need to work with Y". Conceptually, your code "knows" certain things.

Therefore you need a way to denote those things also on the other side. The straight forward way is that the code knows the keys that are used in the property file. In order to isolate that knowledge, you can follow best practices, such as: making the keys a constant in code, and making sure that they are only defined (and ideally: used) only in one class.

Beyond that, of course you can do "meta programming". Meaning: you could program a GUI, and name a label element label-foo ... and then you add some magic that looks into property files, and looks at all the keys in that file. And then "automatically" figures that the property key label-foo-text should be used for the GUI label element label-foo.

So, the answer is: not really. When your information sits in multiple places, then you need some sort of mechanism to bring together what semantically belongs together.

Upvotes: 3

Related Questions