5

I have noticed in a lot of code lately that people put hard coded configuration (like port numbers, etc.) values deep inside of classes/methods, making it difficult to find, and also not configurable.

Is this a violation of the SOLID principles? If not, is there another "principle" that I can cite to my team members about why it's not a good idea? I don't want to just say "it's bad because I don't like it" but I am having trouble thinking of a good argument.

Charles
  • 50,943
  • 13
  • 104
  • 142
skb
  • 30,624
  • 33
  • 94
  • 146

4 Answers4

3

A good argument against hardcoding a TCP port number in a class would be 'Context independence' violation. From GOOS, with my emphasis:

Context Independence

... the "context independence" rule helps us decide whether an object hides too much or hides the wrong information. A system is easier to change if its objects are context-independent; that is, if each object has no built-in knowledge about the system in which it executes. This allows us to take units of behavior (objects) and apply them in new situations. To be context-independent, whatever an object needs to know about the larger environment it’s running in must be passed in.

In this specific case of Context Independence I would call it 'Environment Independence'. In other words a class with hardcoded port number has inappropriate dependency on a runtime OS environment, essentially stating 'I know that port 7778 will always be available' which is clearly wrong.

Dmitry
  • 17,078
  • 2
  • 44
  • 70
0

The SOLID principles cover class design.

I suspect the idea that you should store configuration in configuration files isn't normally regarded as controversial enough to warrant inventing a special principle to persuade people! :)

Most people just figure it out from experience, the first time they try get the software running anywhere other than their own development workstation.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
0

While not strictly SOLID, another principle of OOD is the The Common Closure Principle, which states that classes that change together are packaged together. While not exactly a class, you could stretch this idea to configuration information. Since e.g. port numbers change based on different criteria than the surrounding code, it seems to violates this.

ataylor
  • 64,891
  • 24
  • 161
  • 189
0

The Single Responsibility Principle (the S in SOLID) states that a class should only have one reason to change. This article gives an example of a Modem interface, and discusses how the details of how to connect and hang up are a separate responsibility from the communication of data, and will probably change for different reasons. You could use this to make a similar case for why port numbers are an extra "reason for change", separate from the class's main responsibility.

Neil Vass
  • 5,251
  • 2
  • 22
  • 25