Skip to content

格式化字符串方法需要更灵活的处理策略 #304

@CodeCasterX

Description

@CodeCasterX

功能摘要 / Feature Summary

增强StringUtils.format方法,支持灵活的缺失参数处理策略

功能类型 / Feature Type

API改进 / API Enhancement

优先级 / Priority

中 - 有了更好 / Medium - Would be nice to have

问题描述 / Problem Description

当前StringUtils.format方法在处理缺失参数时只有两种模式:

  1. 严格模式:缺失参数直接抛出异常
  2. 非严格模式:允许多余参数,但缺失参数仍然抛异常

这种设计在实际应用中存在一些限制:

  • 处理日志模板时,希望缺失参数使用空字符串而不是抛异常
  • 处理配置文件模板时,希望缺失参数使用统一的默认值
  • 处理混合格式文本(如包含JSON的YAML)时,希望保持未匹配的占位符原样显示
  • 需要传递两个独立参数(严格性 + 缺失参数策略)使API复杂化

建议的解决方案 / Proposed Solution

设计一个融合的ParameterizationMode枚举,将严格性和缺失参数处理策略整合:

  1. STRICT: 严格模式,缺失参数抛异常(保持现有默认行为)
  2. LENIENT_EMPTY: 宽松模式,缺失参数使用空字符串
  3. LENIENT_DEFAULT: 宽松模式,缺失参数使用指定默认值
  4. LENIENT_KEEP_PLACEHOLDER: 宽松模式,缺失参数保持占位符
  5. LENIENT_STRICT_PARAMETERS: 混合模式,允许多余参数但缺失参数仍抛异常

新增API:

  • format(String, ParameterizationMode, Map) - 使用指定模式
  • format(String, ParameterizationMode, Map, String) - 使用指定模式和默认值
  • formatLenient(String, Map) - 便捷方法,使用空字符串
  • formatLenientWithDefault(String, Map, String) - 便捷方法,使用默认值
  • formatKeepPlaceholder(String, Map) - 便捷方法,保持占位符

替代方案 / Alternative Solutions

  1. 保持当前的两个boolean参数设计
  2. 分别提供不同的方法名如formatWithEmpty、formatWithDefault等
  3. 使用Builder模式配置格式化选项

确认事项 / Confirmations

  • 我已经搜索了现有的 issues 和讨论,确认这不是重复建议
    I have searched existing issues and discussions, confirming this is not a duplicate suggestion

  • 这个功能符合项目的目标和范围
    This feature aligns with the project's goals and scope

  • 我理解这个功能可能需要时间来实现
    I understand this feature may take time to implement

  • 我愿意协助实现这个功能 (可选)
    I'm willing to help implement this feature (optional)

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions