魔数、默认值使用常量封装。提高可读性,统一定义唯一来源,唯一来源相当于是统一了标准。常量在离使用代码最近的地方定义比较好。

现象

const (
	// NamespaceDefault means the object is in the default namespace which is applied when not specified by clients
	NamespaceDefault string = "default"
	// NamespaceAll is the default argument to specify on a context when you want to list or filter resources across all namespaces
	NamespaceAll string = ""
	// NamespaceNodeLease is the namespace where we place node lease objects (used for node heartbeats)
	NamespaceNodeLease string = "kube-node-lease"
)

这是 k8s 的 core 的 type 资源定义。

这个常量定义非常好

  1. 提高可读性;
  2. 统一定义,唯一来源,比如 ALL 到底是 "" 还是 “all”,如果没有这个常量,就得翻全量代码;
  3. 唯一来源,如果后面真好修改,一个地方修改。

唯一来源相当于是统一了标准。

常量在哪里定义

另外,常量定义不用单独一个文件定义,在离使用代码最近的地方定义比较好,容易找。

k8s 源码写得好。

小结

  • 魔数、默认值使用常量封装;
  • 提高可读性;
  • 统一定义,唯一来源;
  • 唯一来源相当于是统一了标准;
  • 常量在离使用代码最近的地方定义比较好,容易找。