Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to hardcode settings in a class?

Tags:

java

oop

I have an array of configs that while they may possibly change in the future, the likelihood is that they will never have to be changed.

If any are missing or incorrect then a certain feature of my system will not work correctly.

Should these still be retrieved be some sort of config, either xml, database etc and made available to the end user to change - or is this a good situation where it makes more sense to hard code them in the class that uses them?

I have spent a long time changing mind over and over on this.

like image 919
Marty Wallace Avatar asked Sep 02 '13 11:09

Marty Wallace


3 Answers

Designer's estimate of the likelihood of something needing to change is not a reliable criterion to make a decision, because real-world use of our programs has its peculiar ways of proving us wrong.

Instead of asking yourself "how likely is something to change?", ask yourself "does it make sense for an end-user to make a change?" If the answer is "yes", make it user-changeable; otherwise, make it changeable only through your code.

A particular mechanism through which you make something changeable (a database, a configuration file, a custom XML file, and so on) does not matter much. An important thing is to have good defaults for settings that are missing, so that your end-users would have harder time breaking your system by supplying partial configurations.

like image 117
Sergey Kalinichenko Avatar answered Oct 16 '22 07:10

Sergey Kalinichenko


Best practice is to use any kind of config or properties file and use default values and failsafe if the file is damaged/missing. These approach has the following advantages:

  • It can easily be recognised as a config file meaning another dev would not need to dive through your classes to change a parameter
  • property files can be written by build tools like ant, so if you have e.g. a test server address and a productive server address the ant task could change the content accordingly
  • it works with default values even without it

Disadvantage is the added complexity.

like image 20
Patrick Favre Avatar answered Oct 16 '22 05:10

Patrick Favre


Yes, it's almost certainly a bad idea to hard-code them; if nothing else, it can make testing (whether automated or manual) a lot more difficult than it needs to be. It's easy to include a .properties file in your jar with the usual defaults, and changing them in the future would just require overriding them at runtime. Dependency injection is usually an even better choice if you have the flexibility to arrange it.

like image 26
chrylis -cautiouslyoptimistic- Avatar answered Oct 16 '22 06:10

chrylis -cautiouslyoptimistic-