Question

I am having a class A which gets a configuration file doing:

this.getClass().getResource("cfgFile");

Now I created a new class B who needs A's cfgFile. Right now I am doing:

A.class.getResource("cfgFile");

But it doesn't feel right.

I was willing to create a new class, something like ABCfg and adding the cfgFile to it's resource path, but I'm not sure it's the best way.

What's the best way to do this?

Thanks for reading!

Was it helpful?

Solution

You should probably create some sort of Configuration class or provide another way for getting configuration data. B shouldn't rely on knowing where A's configuration is, or even that it need's A's configuration. I suggest you look into Dependency Injection.

For example, B could be constructed with the configuration that it needs to do its job, rather than making B responsible for knowing where to find its configuration. The latter approach leads to tightly coupled code which gets to be increasingly hard to test.

OTHER TIPS

You could encapsulate this by wrapping the getClass().getResource() in a new static method on A. This way you have flexibility to change the implementation in the future without affecting calling code.

If A has other responsibilities over providing configuration information then you'd be better off creating a new class just for this. Encapsulating the getResource() call is still worth doing, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top