You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写清晰易读的字符串格式化函数

代码优化方案

原实现存在两个明显的可优化点:

  • 重复执行相同的条件判断,既重复读取request.data的字段,又重复比对枚举值,逻辑冗余
  • 占位符和传入参数的对应关系不直观,需要顺着三元表达式推导才能知道两个位置分别填什么内容,后续改参数顺序很容易出错

方案1:最小成本优化,适配当前仅两种Box的场景

先抽离公共变量消除重复判断,用f-string替代format提升可读性,不需要改动原有业务逻辑:

current_box_type = request.data.get('box_type')
# 先确定当前选中的Box,仅做一次枚举判断
selected_box = 'Box2' if current_box_type == Box.BoxType.Box2 else 'Box3'
# 另一个Box直接基于已确定的selected_box推导,不需要再重复判断枚举
opposite_box = 'Box3' if selected_box == 'Box2' else 'Box2'

confirm_prompt = (
    f'The items included in the {selected_box} are exactly the same as the items in the {opposite_box}. '
    f'Do you want to proceed?'
)

方案2:可扩展优化,适配后续可能新增Box类型的场景

如果后续可能新增更多Box类型,不要硬写三元判断,用映射表维护对应关系,把规则和业务逻辑解耦:

# 映射表可以定义为常量,放在枚举类同级或者配置文件中,统一维护
# Box枚举值到展示名的映射
BOX_NAME_MAP = {
    Box.BoxType.Box2: 'Box2',
    Box.BoxType.Box3: 'Box3'
}
# 配对关系映射:内容互相对比的两个Box
BOX_PAIR_MAP = {
    'Box2': 'Box3',
    'Box3': 'Box2'
}

# 业务逻辑处
current_box_type = request.data.get('box_type')
selected_box = BOX_NAME_MAP[current_box_type]
opposite_box = BOX_PAIR_MAP[selected_box]

confirm_prompt = (
    f'The items included in the {selected_box} are exactly the same as the items in the {opposite_box}. '
    f'Do you want to proceed?'
)

如果需要处理box_type不在枚举范围内的异常场景,可以在取映射值的时候加默认值,或者提前做参数校验。


方案3:封装为可复用函数

如果这段提示语生成逻辑在多处用到,可以封装为独立函数,进一步提升复用性:

def generate_box_duplicate_confirm_prompt(selected_box: str, compare_box: str) -> str:
    """生成Box内容重复的操作确认提示
    :param selected_box: 用户当前操作选中的Box名称
    :param compare_box: 与选中Box内容完全一致的对比Box名称
    """
    return (
        f'The items included in the {selected_box} are exactly the same as the items in the {compare_box}. '
        f'Do you want to proceed?'
    )


# 业务调用示例
current_box_type = request.data.get('box_type')
selected_box = 'Box2' if current_box_type == Box.BoxType.Box2 else 'Box3'
opposite_box = 'Box3' if selected_box == 'Box2' else 'Box2'
confirm_prompt = generate_box_duplicate_confirm_prompt(selected_box, opposite_box)

优化收益

  • 所有判断逻辑只执行一次,不会出现两处判断逻辑不一致的低级bug
  • 变量名自带语义,不需要读条件推导就能知道每个位置传的是什么值
  • 后续调整文案、新增Box类型时只需要修改对应位置的逻辑,不需要在字符串传参处改多处
  • f-string直接把变量写在占位符位置,不需要数参数顺序,可读性远高于裸format传参

内容的提问来源于stack exchange,提问作者BotBot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:34:47