solid-principles - SOLID 原理,以及类内的硬编码配置

标签 solid-principles magic-numbers

我最近在很多代码中注意到人们将硬编码的配置(如端口号等)值放在类/方法的深处,使其难以找到,也无法配置。

这是否违反了 SOLID 原则?如果不是,我是否可以向我的团队成员引用另一个“原则”来说明为什么这不是一个好主意?我不想只是说“这很糟糕,因为我不喜欢它”,但我很难想出一个好的论点。

最佳答案

反对在类中硬编码 TCP 端口号的一个很好的论据是违反“上下文独立性”。来自 GOOS ,我的重点是:

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.



在此特定情况下 Context Independence我称之为“环境独立”。换句话说,具有硬编码端口号的类对运行时操作系统环境有不适当的依赖性,本质上说“我知道端口 7778 将始终可用”,这显然是错误的。

关于solid-principles - SOLID 原理,以及类内的硬编码配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16448076/

相关文章:

oop - IS-A 和 Liskov 替换原则的区别?

java - 这个先决条件是否违反了里氏替换原则

c# - 如何克服从数据库插入方法设计挑战返回 ID

c++ - 反射格雷码到二进制转换中的魔数(Magic Number)

objective-c - SOLID 原则如何应用于 Objective-C 中的方法覆盖?

oop - 单一职责原则(SRP)和我的服务等级

magic-numbers - 23,148,855,308,184,500 是一个神奇的数字,还是纯粹的偶然?

magic-numbers - 为 0 和 1 定义常量

bit-manipulation - 这种神奇的位计数方法是如何工作的?

c# - 使用 .Net 框架判断文件是否为图像,而不是通过检查魔数(Magic Number)