如何消除SHA256/SHA512哈希计算函数中的代码重复?
重构重复的SHA哈希计算代码为通用函数
核心思路
把哈希算法类型(sha256/sha512)作为参数传入通用函数,替代原来重复的专属函数,同时放弃全局变量,改用返回值传递计算结果,让代码更简洁可维护。
具体重构步骤
1. 编写通用哈希计算模块
创建一个通用模块(比如hash_utils.py),把重复的计算逻辑抽成通用函数:
import hashlib def get_hash(hash_algorithm, filename): # 根据算法名称获取对应的哈希对象 hash_obj = hashlib.new(hash_algorithm) with open(filename, "rb") as f: for byte_block in iter(lambda: f.read(4096), b""): hash_obj.update(byte_block) return hash_obj.hexdigest() def verify_checksum(calculated_hash, expected_hash, hash_algorithm): # 通用校验逻辑,对比计算哈希与预期值 if calculated_hash == expected_hash.lower(): print(f"{hash_algorithm} 校验匹配!") else: print(f"{hash_algorithm} 校验不匹配!")
2. 简化主程序逻辑
修改simple_sha_find.py,去掉对两个专属模块的依赖,直接调用通用函数:
import sys from hash_utils import get_hash, verify_checksum # 假设Color和color_reset来自你的颜色工具模块,比如color_utils.py from color_utils import Color, color_reset def which_hash(): sha_type = input("Which hash do you want to calculate: sha256 or sha512? \n").strip().lower() if sha_type not in ["sha256", "sha512"]: print("Type either sha256 or sha512. If you type anything else the program will close...like this.") sys.exit() filename = input("Enter the file name: ") try: calculated_hash = get_hash(sha_type, filename) print(Color.DARKCYAN + f"{sha_type} value has been calculated") color_reset() # 执行校验流程 expected_hash = input(f"Enter the expected {sha_type} checksum: ").strip() verify_checksum(calculated_hash, expected_hash, sha_type) except FileNotFoundError: print(f"Error: 文件 {filename} 不存在") sys.exit() if __name__ == "__main__": which_hash()
3. 清理冗余文件
直接删除原来的sha256.py和sha512.py,通用函数已完全覆盖它们的功能。
重构后的优势
- 彻底消除重复代码,新增其他哈希算法(如sha1)只需在主程序的判断列表中添加,无需新增函数
- 避免全局变量带来的逻辑混乱,结果传递更安全可控
- 模块职责更单一:
hash_utils.py专注哈希计算,主程序专注用户交互与流程控制
内容的提问来源于stack exchange,提问作者codingbt
相关产品推荐
相关产品推荐

