编程范式
1、编程语言
1.1 C/C++
面向对象编程(Object-oriented programming)的核心在于抽象,提供清晰的对象边界。结合封装、集成、多态特性,降低了代码的耦合度,提升了系统的可维护性。C++ 和 之后的 Java 成为主流。
人们将领域问题又开始映射成实体及关系(程序 = 实体 + 关系),而不再是数据结构和算法(过程)了,这就是面向对象编程,核心特点是封装、继承和多态。
1.2 Lisp
函数式语言代表:
·与机器无关
·代码即数据
·闭包
1.3 JavaScript
基于原型和头等函数的多范式语言
·过程式
·面向对象
·函数式
·响应式
总结:
1、编程范式
最常用的范式有三个:过程式编程,面向对象编程(OOP),函数式编程(FP)。
过程式编程的核心在于模块化,在实现过程中使用了状态,依赖了外部变量,导致很容易影响附近的代码,可读性较少,后期的维护成本也较高。
代码问题
- 1.逻辑冗长,局部修改必须阅读整段代码
- 2.对外部变量有依赖
- 3.内部存在共享变量
- 4.函数内部存在临时变量
函数式编程的核心在于“避免副作用”,不改变也不依赖当前函数外的数据。结合不可变数据、函数是第一等公民等特性,使函数带有自描述性,可读性较高。
关键部分实现代码
def get_shannon_info(output):
"""查询shannon类型flash卡信息
"""
lines = checks_string_split_by_function(output, is_shannon_flash_device)
info = map(parser_shannon_info, lines)
# map(lambda x: x.setdefault("type", "shannon"), info)
for item in info:
item["type"] = "shannon"
data = map(modify_the_properties, info)
return reduce(combining_data, map(convert_data_format, data))
面向对象编程的核心在于抽象,提供清晰的对象边界。结合封装、集成、多态特性,降低了代码的耦合度,提升了系统的可维护性。 关键部分实现代码
class IFlash(six.with_metaclass(abc.ABCMeta)):
def __init__(self):
pass
@abc.abstractmethod
def collect(self):
"""收集flash卡物理信息
"""
pass
class FlashShannon(IFlash):
"""宝存的Flash卡
"""
def __init__(self, txt_path, command, printer):
super(FlashShannon, self).__init__()
self.txt_path = txt_path
self.command = command
self.printer = printer
def collect(self):
result = {}
for info in self._get_shannon_info():
life_left = str(info.get("estimated_life_left", "")).replace("%", "")
temperature = info.get("controller_temperature", "")
error_msg = self._get_health_message(life_left, temperature)
sub_info = {
"available_capacity": info.get("disk_capacity", ""),
"device_name": info.get("block_device_node", ""),
"firmware_version": info.get("firmware_version", ""),
"interface": "PCIe",
"life_left": life_left,
"pcie_id": info.get("pci_deviceid", ""),
"pcie_length": "",
"pcie_type": "",
"physical_read": info.get("host_read_data", ""),
"physical_write": info.get("total_write_data", ""),
"serial_number": info.get("serial_number", ""),
"temperature": temperature,
"type": info["type"],
"error_msg": error_msg,
"status": "ok" if error_msg == "healthy" else "error"
}
if sub_info["serial_number"]:
result[sub_info["serial_number"]] = sub_info
else:
result[sub_info["device_name"]] = sub_info
return result
class FlashFio(IFlash):
"""fio的Flash卡
"""
def __init__(self, txt_path):
super(FlashFio, self).__init__()
self.txt_path = txt_path
def collect(self):
disk_info = {}
adapter_info = self._get_adapter_info()
for info in adapter_info:
serial_number = info["fio_serial_number"]
for io in info["iomemory"]:
data = self._combining_io_memory(io)
data["serial_number"] = serial_number
disk_info[serial_number] = data
return disk_info
不同的范式的出现,目的就是为了应对不同的场景,但最终的目标都是提高生产力。
个人总结
C++支持多种编程范式,包括函数式、面向过程、面向对对象、泛型编程,所以这几种范式都要掌握。但是在开发普通的应用程序的过程中,了解面向过程、面向对象、函数式编程就能解决大多数问题了,但是如果是开发面向程序员的库,那么就有必要深入了解一下泛型编程了。